如果列包含逗号分隔值,请创建单独的行

时间:2014-12-16 05:32:46

标签: sql sql-server sql-server-2008 multiple-columns

假设我们有一个简单的选择查询,返回结果如下

   FirstName          LastName                     PayScale
   -----------        ------------                ---------------
    Craig              L                             150000
    Alice,Lisa         simons                        100000

因此,如果我们使用逗号分隔的名字,那么我想要这样的结果

   FirstName          LastName                     PayScale
   -----------        ------------                ---------------
    Craig              L                             150000
    Alice              simons                        100000
    Lisa               simons                        100000

1 个答案:

答案 0 :(得分:3)

您可以将查询编写为:

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)