Extracting First Name and Last Name

前端 未结 3 822
余生分开走
余生分开走 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
    

提交回复
热议问题