Split Name / Split String
One common task performed in database applications is given a full name, how can
this be split into the first name and last name. In this article, three
different methods are discussed to perform this task using three different
functions in SQL Server. It is assumed in this article that the full name
is just made up of one first name and one last name.
Using SUBSTRING Function
The first method is the use of the SUBSTRING string function, as can be seen
from the following script:
DECLARE @FullName VARCHAR(100)
SET @FullName = 'John Doe'
SELECT SUBSTRING(@FullName, 1, CHARINDEX(' ', @FullName) - 1) AS [FirstName],
SUBSTRING(@FullName, CHARINDEX(' ', @FullName) + 1, LEN(@FullName)) AS [LastName]
Given the full name of "John Doe", the script will generate the following output:
FirstName LastName
------------ ----------------
John Doe
Aside from the SUBSTRING string function, it also used the CHARINDEX string
function. The CHARINDEX function returns the starting position of a
specified expression in a character string. The CHARINDEX function was
used to look for the space that separates the first name from the last name (CHARINDEX('
', @FullName)).
If the full name only contains the last name, the following error message will
be encountered:
Server: Msg 536, Level 16, State 3, Line 4
Invalid length parameter passed to the substring function.
To avoid this error message, the script above needs to be modified to check if
there's a space in the full name. If there's no space in the full name,
it is assumed that it only contains the last name. The following script
overcomes this problem:
DECLARE @FullName VARCHAR(100)
SET @FullName = 'JohnDoe'
SELECT SUBSTRING(@FullName, 1, NULLIF(CHARINDEX(' ', @FullName) - 1, -1)) AS [FirstName],
SUBSTRING(@FullName, CHARINDEX(' ', @FullName) + 1, LEN(@FullName)) AS [LastName]
The only difference between this script and the previous one is the addition of
the NULLIF function. The NULLIF function returns a null value if the two
specified expressions are equivalent. In the CHARINDEX function, if the
space is not found in the full name, it returns a value of 0. Then
subtracting 1 from this gives a value of -1. Using the NULLIF function,
we are changing the length parameter passed to the SUBSTRING function to NULL
if the value returned by the CHARINDEX minus 1 is -1. In the SUBSTRING
function if the length parameter is NULL, the string returned is NULL as
well. Therefore, if there's no space in the full name, the first name
will have a value of NULL, as shown in the following result:
FirstName LastName
------------ ----------------
NULL JohnDoe