Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse file name and path from full path

I need to parse file name and file path from full path using SQL Query.

Eg. Fullpath - \SERVER\D$\EXPORTFILES\EXPORT001.csv

FileName        Path
EXPORT001.csv   \\SERVER\D$\EXPORTFILES\
like image 546
Don Avatar asked Oct 21 '13 22:10

Don


People also ask

How do I get the filename from the file path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);

How do I separate the filename and path in Python?

split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that. In the above example 'file. txt' component of path name is tail and '/home/User/Desktop/' is head.


3 Answers

Use this -

DECLARE @full_path VARCHAR(1000)
SET @full_path = '\\SERVER\D$\EXPORTFILES\EXPORT001.csv'

SELECT LEFT(@full_path,LEN(@full_path) - charindex('\',reverse(@full_path),1) + 1) [path], 
       RIGHT(@full_path, CHARINDEX('\', REVERSE(@full_path)) -1)  [file_name]
like image 152
AgentSQL Avatar answered Oct 22 '22 03:10

AgentSQL


I do a lot of ETL work and I was looking for a function that I could use and qub1n's solution works very good except for values without a back slash. Here is a little tweak of qub1n's solution that will handle strings without back slashes:

Create FUNCTION fnGetFileName
(
    @fullpath nvarchar(260)
) 
RETURNS nvarchar(260)
AS
BEGIN
    IF(CHARINDEX('\', @fullpath) > 0)
       SELECT @fullpath = RIGHT(@fullpath, CHARINDEX('\', REVERSE(@fullpath)) -1)
       RETURN @fullpath
END

Samples:

    SELECT [dbo].[fnGetFileName]('C:\Test\New Text Document.txt') --> New Text Document.txt
    SELECT [dbo].[fnGetFileName]('C:\Test\Text Docs\New Text Document.txt') --> New Text Document.txt
    SELECT [dbo].[fnGetFileName]('New Text Document.txt') --> New Text Document.txt
    SELECT [dbo].[fnGetFileName]('\SERVER\D$\EXPORTFILES\EXPORT001.csv') --> EXPORT001.csv

Here is a LINK to SqlFiddle

like image 31
Mark Kram Avatar answered Oct 22 '22 02:10

Mark Kram


Answer based on comment by Stefan Steiger:

Create FUNCTION GetFileName
(
 @fullpath nvarchar(260)
) 
RETURNS nvarchar(260)
AS
BEGIN
DECLARE @charIndexResult int
SET @charIndexResult = CHARINDEX('\', REVERSE(@fullpath))

IF @charIndexResult = 0
    RETURN NULL 

RETURN RIGHT(@fullpath, @charIndexResult -1)
END
GO

Test code:

DECLARE @fn nvarchar(260)

EXEC @fn = dbo.GetFileName 'AppData\goto\image.jpg'
PRINT @fn -- prints image.jpg

EXEC @fn = dbo.GetFileName 'c:\AppData\goto\image.jpg'
PRINT @fn -- prints image.jpg

EXEC @fn = dbo.GetFileName 'image.jpg'
PRINT @fn -- prints NULL
like image 7
Tomas Kubes Avatar answered Oct 22 '22 02:10

Tomas Kubes