Sql查询创建单行到多行

时间:2014-09-04 13:10:14

标签: sql sql-server sql-server-2008

我有一张表格,如下所示

ID           Value
-----        ----------
1            10,20,30 

我需要结果

ID         Value
---        -------
1           10
1           20
1           30

感谢。

2 个答案:

答案 0 :(得分:0)

这将有效

  ;with tmp(Id, value, Data) as (
select Id,  LEFT(value, CHARINDEX(',',value+',')-1),
    STUFF(value, 1, CHARINDEX(',',value+','), '')
from @Testdata
union all
select Id, LEFT(Data, CHARINDEX(',',Data+',')-1),
    STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from tmp
where Data > ''
)
select Id,  value
from tmp
order by Id

可能重复Turning a Comma Separated string into individual rows

答案 1 :(得分:0)

请尝试以下方法:

 SELECT A.ID,  
        Split.a.value('.', 'VARCHAR(100)') AS Value  
   FROM (SELECT ID,  
              CAST ('<V>' + REPLACE(Value, ',', '</V><V>') + '</V>' AS XML) AS Value  
         FROM  YourTable
        ) AS A 
        CROSS APPLY Value.nodes ('/V') AS Split(a);