2011-05-14 101 views
3

我如何可以查詢表,看起來像這樣:TSQL拆分XML節點

DECLARE @test as table (
    [Id] int, 
    [Changes] XML 
    ) 

insert into @test VALUES (1,'<insert pk="1"/><insert pk="2"/><delete pk="1"/><delete pk="2"/>') 
insert into @test VALUES (2,'<insert pk="3"/>') 

爲了得到這個輸出?

1, <insert pk="1"/> 
1, <insert pk="2"/> 
1, <delete pk="1"/> 
1, <delete pk="2"/> 
2, <insert pk="3"/> 

回答

4

嘗試這樣:

SELECT 
    ID, 
    XmlChanges.query('.') 
FROM 
    @test 
CROSS APPLY 
    Changes.nodes('/*') AS Nodes(XmlChanges) 

輸出結果將是:

ID (No column name) 
1 <insert pk="1" /> 
1 <insert pk="2" /> 
1 <delete pk="1" /> 
1 <delete pk="2" /> 
2 <insert pk="3" /> 
+0

正是我一直在尋找,謝謝! – StormRider01 2011-05-14 17:28:52