我有一个带有XML列的SQL表。该列的值如下所示:
<StudentGroup xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<StudentIds>
<int>3000</int>
<int>3001</int>
<int>3002</int>
<int>8</int>
<int>9</int>
</StudentIds>
</StudentGroup>
我想在单独的一行而不是一行中获取每个StudentID。这是我所做的:
select
xmlColumn.value('(/StudentGroup/StudentIds)[1]','varchar(max)') as IDs
from myTable
此select语句在一行中返回ID。像这样:
30003001300289
想要的是
3000
3001
3002
8
9
请帮忙!提前致谢。
最佳答案
在变量中包含XML时:
DECLARE @x XML = '
<StudentGroup xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<StudentIds>
<int>3000</int>
<int>3001</int>
<int>3002</int>
<int>8</int>
<int>9</int>
</StudentIds>
</StudentGroup>';
SELECT
n.v.value('.','INT') AS ID
FROM
@x.nodes('/StudentGroup/StudentIds/int') AS n(v);
在表中有XML时:
DECLARE @x XML = '
<StudentGroup xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<StudentIds>
<int>3000</int>
<int>3001</int>
<int>3002</int>
<int>8</int>
<int>9</int>
</StudentIds>
</StudentGroup>';
DECLARE @t TABLE(
x XML
);
INSERT INTO @t(x)VALUES(@x);
SELECT
n.v.value('.','INT') AS ID
FROM
@t
CROSS APPLY x.nodes('/StudentGroup/StudentIds/int') AS n(v);
关于sql - 将XML节点值分成SQL中的单独行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40349330/