User Defined Function (UDF) to Remove the File Name from a Path in SQL Server

To create a User Defined Function (UDF) that accepts a string with the full path and returns the path without the file name and extension, use the following command:

CREATE FUNCTION ufnPath (@MyString nvarchar(512))
RETURNS nvarchar(256)
AS
BEGIN
DECLARE @ReturnString nvarchar(256)
SET @ReturnString = LEFT(@MyString, LEN(@MyString) - charindex('\',reverse(@MyString),1) + 1)
RETURN @ReturnString
END
GO

To use this user-defined function:

SELECT dbo.ufnPath ('D:\sql\temp\code.txt')

ufnPath

To see how to Get the File Name from a Path in SQL Server:
User Defined Function (UDF) to Get the File Name from a Path in SQL Server

If the post helped you, please share it:
Pin It

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">