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