Extracting First Name and Last Name

前端 未结 3 823
余生分开走
余生分开走 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:16
    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-18 08:24

    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

    0 讨论(0)
提交回复
热议问题