将xml从SQL中的不同xml元素展平为列

时间:2014-03-14 18:17:03

标签: sql xml sqlxml

我有以下XML

<creatures>
    <Animals>
        <Name>Dog</Name>
        <Name>Cat</Name>
        <Name>Monkey</Name>
    </Animals>
    <NumLegs>
        <Legs>4</Legs>
        <Legs>4</Legs>
        <Legs>2</Legs>
    </NumLegs>
</creatures>

需要如下表格

Name    Legs
 Dog    4 
 Cat    4
 Monkey 2

我如何在SQL中执行此操作?我在这个主题上发现的所有其他问题都有不同的XML结构。对于例如如果XML的结构如下,我相信使用nodes()

在XML中解析它是很简单的
<creatures>
      <Animal>
           <Name>Dog</Name>
           <Legs>4</Legs>
      </Animal>
      .
      .
      .
 </creatures>

1 个答案:

答案 0 :(得分:0)

您可以为两个集合中的每一行生成索引,然后加入:

declare @xml xml
set @xml =
'<creatures>
    <Animals>
        <Name>Dog</Name>
        <Name>Cat</Name>
        <Name>Monkey</Name>
    </Animals>
    <NumLegs>
        <Legs>4</Legs>
        <Legs>4</Legs>
        <Legs>2</Legs>
    </NumLegs>
</creatures>'

-- create a table of the animals with an index generated by an identity
declare @animals table(n tinyint not null identity(1, 1), animal nvarchar(50) not null)
insert @animals (animal)
select
    a.n.value('.', 'nvarchar(50)')
from
    @xml.nodes('/creatures/Animals/Name') a(n)

-- create a table of the leg amounts with an index generated by an identity
declare @legs table(n tinyint not null identity(1, 1), amount tinyint not null)
insert @legs (amount)
select
    nl.l.value('.', 'tinyint')
from
    @xml.nodes('/creatures/NumLegs/Legs') nl(l)

-- bring together the 2 tables based on the index
select
    a.animal, l.amount
from
    @animals a
    join @legs l
        on a.n = l.n