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

将SQL中不同xml元素的xml展平为列,sql,xml,sqlxml,Sql,Xml,Sqlxml,我有以下XML <creatures> <Animals> <Name>Dog</Name> <Name>Cat</Name> <Name>Monkey</Name> </Animals> <NumLegs> <Legs>4</Legs> <Le

我有以下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>
如何在SQL中实现这一点?我在这个主题上发现的所有其他问题的XML结构都不同。例如,如果XML的结构如下所示,我相信使用节点在XML中解析它是很简单的

<creatures>
      <Animal>
           <Name>Dog</Name>
           <Legs>4</Legs>
      </Animal>
      .
      .
      .
 </creatures>

您可以为两个集合中的每一行生成索引,然后在该集合上进行联接:

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

非常感谢。这是非常有帮助的。
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