User Defined Function (UDF) to get the Last Name from a Full Name in SQL Server

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

CREATE FUNCTION ufnLastName (@MyString nvarchar(256))
RETURNS nvarchar(128)
AS
BEGIN
DECLARE @ReturnString nvarchar(64)
SET @ReturnString = RIGHT(@MyString, CHARINDEX(' ', REVERSE(@MyString)) - 1)
RETURN @ReturnString
END
GO

To use this user-defined function:

SELECT dbo.ufnLastName ('John Smith')

ufnLastName_full_name

The function can also be used to get the last word from the sentence:

SELECT dbo.ufnLastName ('This function returns the last word of the sentence')

ufnLastName_sentence

To see how to create a User Defined Function (UDF) to get the First Name from a Full Name in SQL Server:
User Defined Function (UDF) to get the First Name from a Full Name 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="">