如何将XML插入SQL

时间:2015-04-27 11:52:56

标签: sql sql-server xml sql-server-2008

我尝试将XML文件添加到SQL 2008中。

我的XML:

<ItemList>
    <Section Index="0" Name="cat0">
        <Item Index="0" Slot="0" />
        <Item Index="1" Slot="0" />
    </Section>
    <Section Index="1" Name="cat1">
        <Item Index="33" Slot="0" />
        <Item Index="54" Slot="0" />
    </Section>
        <Section Index="2" Name="cat2">
        <Item Index="55" Slot="0" />
        <Item Index="78" Slot="0" />
    </Section>
</ItemList>

SQL专栏:

Name = Section Name,
Cat = Section Index,
Index = Item Index,
Slot = Item Slot.

我的例子:

DECLARE @input XML = 'MY XML file'

SELECT
      Name = XCol.value('@Index','varchar(25)'),
      Cat = XCol.value('@Name','varchar(25)'),
      [Index] = 'Unknown', /* Index from <Item>*/
      Slot = 'Unknown' /* Slot from <Item> */
FROM @input.nodes('/ItemList/Section') AS test(XCol)

我不知道如何从“Item”中添加值。

非常感谢!

2 个答案:

答案 0 :(得分:3)

你可以这样做:

select
  Name = XCol.value('../@Index','varchar(25)'),
  Cat = XCol.value('../@Name','varchar(25)'),
  [Index] = XCol.value('@Index','varchar(25)'),
  Slot = XCol.value('@Slot','varchar(25)')
from
  @input.nodes('/ItemList/Section/Item') AS test(XCol)

关键想法:将数据提升一级,而不是/ItemList/Section,而是/ItemList/Section/Item。因此,在这种情况下,您可以访问Item的属性,还可以通过指定Section

来访问父元素(在您的案例中为../@Attribute_Name)的属性

答案 1 :(得分:2)

与上一个答案不同 - CROSS APPLY与子项目节点:

SELECT
      Name = XCol.value('@Index','varchar(25)'),
      Cat = XCol.value('@Name','varchar(25)'),
      [Index] = XCol2.value('@Index','varchar(25)'),
      Slot = XCol2.value('@Slot','varchar(25)')
FROM @input.nodes('/ItemList/Section') AS test(XCol)
    CROSS APPLY XCol.nodes('Item') AS test2(XCol2)