假设我有一个返回以下内容的查询
ID SomeValue
1 a,b,c,d
2 e,f,g
我想按如下方式返回:
ID SomeValue
1 a
1 b
1 c
1 d
2 e
2 f
2 g
我已经有一个UDF调用Split,它将接受一个字符串和一个分隔符,并将其作为一个名为[Value]的列的表返回。鉴于此,SQL看起来如何实现这一目标?
答案 0 :(得分:7)
或者,您可以像这样使用XML:
DECLARE @yourTable TABLE(ID INT,SomeValue VARCHAR(25));
INSERT INTO @yourTable
VALUES (1,'a,b,c,d'),
(2,'e,f,g');
WITH CTE
AS
(
SELECT ID,
[xml_val] = CAST('<t>' + REPLACE(SomeValue,',','</t><t>') + '</t>' AS XML)
FROM @yourTable
)
SELECT ID,
[SomeValue] = col.value('.','VARCHAR(100)')
FROM CTE
CROSS APPLY [xml_val].nodes('/t') CA(col)
答案 1 :(得分:1)
您使用cross apply
。像这样:
select t.id, s.val as SomeValue
from table t cross apply
dbo.split(SomeValue, ',') as s(val);
答案 2 :(得分:0)
我知道这是一篇较旧的帖子,但我想添加我的解决方案,以便将来可以找到它。我不得不对Stephan's解决方案稍作调整,以便考虑不包含分隔符的值:
DECLARE @yourTable TABLE(ID INT,SomeValue VARCHAR(25));
INSERT INTO @yourTable
VALUES (1,'a,b,c,d'),
(2,'e'),
(3,'f'),
(4,'g,h,i');
WITH CTE
AS
(
SELECT ID,
[xml_val] = CAST('<t>' +
CASE WHEN CHARINDEX(',', SomeValue) > 0
THEN REPLACE(SomeValue,',','</t><t>')
ELSE SomeValue
END + '</t>' AS XML)
FROM @yourTable
)
SELECT ID,
[SomeValue] = col.value('.','VARCHAR(100)')
FROM CTE
CROSS APPLY [xml_val].nodes('/t') CA(col)