sql >> Base de Datos >  >> RDS >> Sqlserver

Extracción de nombre y apellido

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