Parse Paths in SQL

Just a couple of udf to handle paths in sql server, not very solid but if your paths are valid they work well.

CREATE FUNCTION dbo.GetFileName (@Path varchar(512))  
RETURNS varchar(255) AS  
BEGIN 
	Return    RIGHT(@Path, LEN(@Path) - dbo.LAST_INDEX(@Path, '\')) 
END

CREATE FUNCTION dbo.GetDirectory (@Path varchar(512))  
RETURNS varchar(255) AS  
BEGIN 
	Return    Left(@Path, dbo.LAST_INDEX(@Path, '\')) 
END
CREATE FUNCTION dbo.GetDirectoryName (@Path varchar(512))  
RETURNS varchar(255) AS  
BEGIN 
	Return dbo.GetFilename(Left(@Path, dbo.LAST_INDEX(@Path, '\') -1))
END
CREATE FUNCTION dbo.GetExtension (@Path varchar(512))  
RETURNS varchar(255) AS  
BEGIN 
	Return    RIGHT(@Path, LEN(@Path) - dbo.LAST_INDEX(@Path, '.')) 
END

CREATE FUNCTION dbo.LAST_INDEX(@STRING VARCHAR(1024), @CHAR CHAR)
RETURNS INT
AS
BEGIN
        IF ISNULL(@STRING, '') = '' OR  ISNULL(@CHAR, '') = ''
            RETURN 0  
	DECLARE @pos int
	select @pos = LEN(@STRING) - CHARINDEX(@CHAR, REVERSE(@STRING)) + 1
	IF @pos > len(@string) 
		SELECT @pos = 0
	RETURN @pos
END

Leave a Reply

Your email address will not be published. Required fields are marked *