declare @x xml =
'<Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Tests>
<Test Name="Test1" TotalMarks="100">95</Test>
<Test Name="Test2" TotalMarks="200">65</Test>
<Test Name="Test3" TotalMarks="150">95</Test>
<Test Name="Test4" TotalMarks="150"></Test>
</Tests>
<Tests>
<Test Name="Test1" TotalMarks="100">95</Test>
<Test Name="Test2" TotalMarks="200">65</Test>
<Test Name="Test3" TotalMarks="150">95</Test>
<Test Name="Test4" TotalMarks="150"></Test>
</Tests>
</Detials>'
当我这样查询时
SELECT STUFF(
@x.query('for $a in (*:Detials/Tests/Test/@Name)
return <a>{concat(",", $a)}</a>')
.value('.', 'NVARCHAR(MAX)'),
1, 1, '') AS ListOfName
我是这样的
ListofName
TEST1,Test2的,Test3的,TEST4,TEST1,的Test2,Test3的,TEST4
但是想要根据&lt; 测试&gt;来粉碎xml。哪个可以得到如下结果
ListofName
测试1,Test2的,Test3的,TEST4
TEST1,Test2的,Test3的,TEST4
请在此处帮助我将原始XML分解为单独的行,然后使用query()和value()
进行字符串连接先谢谢Jayendran
答案 0 :(得分:1)
试试这个解决方案:
declare @x xml =
'<Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Tests>
<Test Name="Test1" TotalMarks="100">95</Test>
<Test Name="Test2" TotalMarks="200">65</Test>
<Test Name="Test3" TotalMarks="150">95</Test>
<Test Name="Test4" TotalMarks="150"></Test>
</Tests>
<Tests>
<Test Name="Test1" TotalMarks="100">95</Test>
<Test Name="Test2" TotalMarks="200">65</Test>
<Test Name="Test3" TotalMarks="150">95</Test>
<Test Name="Test4" TotalMarks="150"></Test>
</Tests>
</Detials>'
-- Edit 1
SELECT XmlTable.OriginalID, ROW_NUMBER() OVER(ORDER BY x.XmlCol) AS RowNum, y.ListOfName
FROM (SELECT 1 AS OriginalID, @x AS XmlCol) AS XmlTable -- Edit 2
CROSS APPLY XMLTable.XmlCol.nodes('*:Detials/Tests') AS x(XmlCol)
CROSS APPLY(
SELECT STUFF(x.XmlCol.query('for $a in (Test/@Name) return <a>{concat(",", $a)}</a>').value('.', 'NVARCHAR(MAX)'), 1, 1, '')
) AS y(ListOfName)
-- End of Edit 1
<强> Demo 强>