我想循环遍历SQL Server中的xml节点,并创建包含','的每个节点的副本。
例如,对于以下xml:
declare @answerXML xml = '<answers><answer part="1">answer,test0</answer><answer part="1">answer,test1</answer></answers>'
我希望修改为以下内容:
declare @answerXML xml = '<answers><answer part="1">answer,test0</answer><answer part="1">answer, test0</answer><answer part="1">answer,test1</answer><answer part="1">answer, test1</answer></answers>'
(每个节点都是重复的,在添加的节点中,在逗号后添加空格)。
我正在计划使用这样的东西:
SELECT
T.ref.value('.', 'varchar(256)') AS Answer
FROM
(SELECT
[Xml] = @answerXML.query('for $i in data(/answers/answer)
return element temp { $i }')
) A
CROSS APPLY
A.Xml.nodes('/temp') T(ref)
但没有用,似乎太复杂了。
任何人都可以帮助学习如何在T-SQL中循环和更新XML吗?
提前谢谢你,
答案 0 :(得分:2)
您可以尝试粉碎XML并从头开始重建:
declare @answerXML xml=
'<answers>
<answer part="1">answer,test0</answer>
<answer part="1">answer,test1</answer>
</answers>';
SELECT a.value(N'@part',N'int') AS [answer/@part]
,a.value(N'text()[1]',N'nvarchar(max)') AS [answer]
,''
,a.value(N'@part',N'int') AS [answer/@part]
,REPLACE(a.value(N'text()[1]',N'nvarchar(max)'),',',', ') AS [answer]
FROM @answerXML.nodes(N'/answers/answer') AS A(a)
FOR XML PATH(''),ROOT('answers')
结果
<answers>
<answer part="1">answer,test0</answer>
<answer part="1">answer, test0</answer>
<answer part="1">answer,test1</answer>
<answer part="1">answer, test1</answer>
</answers>