2015-04-27 47 views
2

我嘗試將XML文件添加到SQL 2008如何插入XML到SQL

我的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」中添加值。

非常感謝!

回答

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屬性,你也可以通過指定比以前的答案../@Attribute_Name

+0

非常感謝! – MeTa

2

不同的訪問(在你的情況Section)父元素的屬性 - CROSS與孩子項目節點適用於:

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

非常感謝!我會了解更多關於CROSS APPLY對我來說是新的:) – MeTa