Extracting First Name and Last Name

前端 未结 3 914
余生分开走
余生分开走 2021-01-18 07:56

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:



        
3条回答
  •  时光取名叫无心
    2021-01-18 08:23

    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.

提交回复
热议问题