User Defined Function (UDF) to get the First 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 first name, use the following command:

CREATE FUNCTION ufnFirstName (@MyString nvarchar(256))
RETURNS nvarchar(256)
AS
BEGIN
DECLARE @ReturnString nvarchar(128)
SET @ReturnString = RTRIM(LEFT((@MyString), CHARINDEX(' ', (@MyString))))
RETURN @ReturnString
END
GO

To use this user-defined function:

SELECT dbo.ufnFirstName ('John Smith')

ufnFirstName_full_name

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

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

ufnFirstName_sentence

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