Extracting First Name and Last Name
I have a column named Name in a table called test which has Full name and I am trying to extract First name and Last Name. So I wrote query something like this:
SELECT
[Name],
LEFT([Name],CHARINDEX(' ',[Name])-1) AS FIRST_NAME,
SUBSTRING([Name],CHARINDEX(' ',[Name])+1,开发者_高级运维LEN([Name])) AS LAST_NAME
FROM Test
But It is giving me error saying:
Msg 537, Level 16, State 2, Line 1 Invalid length parameter passed to the LEFT or SUBSTRING function.
Thta's because I have some values in the name like:
Name:
Hopkins
How do I handle these?
Declare @t table ( [Name] varchar(100) )
insert into @t ( Name )
VALUES ( 'dennis hopper' ), ('keanu reaves'), ('thatgirl')
SELECT
[Name],
CHARINDEX(' ', [Name]),
CASE WHEN CHARINDEX(' ', [Name]) > 0 THEN
LEFT([Name],CHARINDEX(' ',[Name])-1)
ELSE
[Name]
END as FIRST_NAME,
CASE WHEN CHARINDEX(' ', [Name]) > 0 THEN
SUBSTRING([Name],CHARINDEX(' ',[Name])+1, ( LEN([Name]) - CHARINDEX(' ',[Name])+1) )
ELSE
NULL
END as LAST_NAME
FROM @t
The problem with your original code is here:
CHARINDEX(' ',[Name])-1
If [Name] does not contain a space, CharIndex returns 0. You subtract 1 and feed this in to the Left function. When the 2nd parameter to the left function is -1, you will get this error. In my opinion, the easiest way to "fix" this problem is to give the CharIndex function something to find, like this:
CHARINDEX(' ',[Name] + ' ')-1
Now... this code cannot fail.
You only NEED to do this one place in your original code, but you should add it to the LAST_NAME part also. If you don't, you will get incorrect results (eventhough you will not get an error).
SELECT [Name],
LEFT([Name],CHARINDEX(' ',[Name] + ' ')-1) AS FIRST_NAME,
SUBSTRING([Name],CHARINDEX(' ',[Name] + ' ')+1,LEN([Name])) AS LAST_NAME
FROM Test
This query will return the same results as the query suggested by @Sage, but (in my opinion) it is easier to read, and easier to understand.
we may also use locate function
SELECT Name, LEFT(Name,locate(' ',Name)-1) AS FIRST_NAME, SUBSTRING(Name,locate(' ',Name)+1,LENgth(Name)) AS LAST_NAME FROM test
精彩评论