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

Haga una fila separada si una columna contiene valores separados por comas

Puede escribir una consulta como:

DECLARE @employee TABLE (FirstName  VARCHAR(100),
                         LastName   VARCHAR(100),
                         PayScale INT)

INSERT INTO @employee VALUES 
('Craig','L',150000) , 
('Alice,Lisa','simons',100000)



SELECT Split.a.value('.', 'VARCHAR(100)') AS FirstName  , LastName  ,PayScale
       FROM  (SELECT  CAST ('<M>' + REPLACE(FirstName, ',', '</M><M>') + '</M>' 
                             AS XML) AS FirstName ,  LastName    ,PayScale
               FROM  @employee) 
       AS A 
CROSS APPLY FirstName.nodes ('/M') AS Split(a)