2016-10-31 26 views
2

我有一个带有XML列的SQL表。该列的值如下所示:在SQL中将单独的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> 

我想要将每个StudentIDs放在单独的行中而不是一行中。这是我所做的:

select 
    xmlColumn.value('(/StudentGroup/StudentIds)[1]','varchar(max)') as IDs 
from myTable 

这个select语句返回一行中的ID。就像这样:

30003001300289 

什么是要的就是

3000 
3001 
3002 
8 
9 

请帮帮忙!提前致谢。

回答

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); 
+0

让我重写了一个表...对不起快海报;) –

+0

谢谢!这正是我所期待的。 – nmess88

+0

@ nmess88不客气=) –

相关问题