TSQL拆分XML节点

时间:2011-05-14 06:16:27

标签: xml tsql sql-server-2008

如何查询看起来像这样的表:

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"/>

1 个答案:

答案 0 :(得分: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" />