2011-06-10 32 views
4

我有一個如下所示的xml數據。查詢@xml變量以獲取行集合

DECLARE @XmlContent XML 
SET @XmlContent = 
'<Entities> 
<Entity type = "5"> 
     <item id ="1"/> 
     <item id ="2"/> 
     <item id ="2"/> 
</Entity> 
<Entity type = "6"> 
     <item id ="3"/> 
     <item id ="4"/> 
     <item id ="5"/> 
</Entity> 
</Entities>' 

我想從這個選擇數據和插入表中以下格式 -

 
------------ 
Type Id 
------------ 
5  1 
5  2 
5  2 
6  3 
6  4 
6  5 

有人能幫助我在SQL Server中編寫查詢呢?

回答

4
select 
    ent.value('@type', 'int') as Type, 
    row.value('@id', 'int') as ID 
from 
    @XmlContent.nodes('/Entities/Entity') foo(ent) 
    cross apply ent.nodes('item') bar(row)