在SQL中将XML节点值分隔为单独的行

时间:2016-10-31 19:36:41

标签: sql sql-server xml xpath

我有一个带有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

请帮忙!提前谢谢。

1 个答案:

答案 0 :(得分:1)

当您在变量中包含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);