我有一些数据如下
Declare @t table (Id int identity,CommaSeperatedValue varchar(100))
Insert Into @t
Select 'Somalia,Vietnam' Union All
Select 'apple,banana,guava,India,Australia'
CommaSeparated 值没有限制。提供的样本的期望输出将是
Id Col1 Col2 Col3 Col4 Col5
1 Somalia Vietnam Null Null Null
2 apple banana guava India Australia
这意味着,列将动态生成。让我们再举一个例子
Declare @t table (Id int identity,CommaSeperatedValue varchar(100))
Insert Into @t
Select 'Somalia,Vietnam,Honolulu,Spain' Union All
Select 'apple,banana,guava,India,Australia,Smart,Bus' Union All
Select 'Mango'
所需的输出
Id Col1 Col2 Col3 Col4 Col5 Col6 Col7
1 Somalia Vietnam Honolulu Spain Null Null Null
2 apple banana guava India Australia Smart Bus
3 Mango Null Null Null Null Null Null
这个查询怎么做?
到目前为止我的尝试(在此之后我迷路了)
SELECT
X.id,
X.CommaSeperatedValue,
Y.splitdata
FROM
(
SELECT *,
CAST('<X>'+REPLACE(F.CommaSeperatedValue,',','</X><X>')+'</X>' AS XML) AS xmlfilter
FROM @t F
)X
CROSS APPLY
(
SELECT fdata.D.value('.','varchar(50)') as splitdata
FROM X.xmlfilter.nodes('X') as fdata(D)
)Y
提前致谢