删除SQL Server XML字段中的多个节点

时间:2011-10-06 18:56:39

标签: xml sql-server-2005 xml-dml

如果在SQL Server 2005中运行此脚本:

create table #xmltemp
(
    id int,
    data xml null
)

insert into #xmltemp
select 1, ''

update #xmltemp
set data.modify('insert <a id="1" /> into /')
update #xmltemp
set data.modify('insert <a id="2" /> into /')
update #xmltemp
set data.modify('insert <a id="3" /> into /')
update #xmltemp
set data.modify('insert <a id="4" /> into /')

select * from #xmltemp

update x
set data.modify('delete //a[@id=sql:column("t.xmlid")]')
from #xmltemp x
inner join (
    select 1 as id, 1 as xmlid union
    select 1 as id, 2 as xmlid union
    select 1 as id, 3 as xmlid
) t on t.id = x.id

select * from #xmltemp

drop table #xmltemp

您将获得以下输出:

id  data
1   <a id="1" /><a id="2" /><a id="3" /><a id="4" />

id  data
1   <a id="2" /><a id="3" /><a id="4" />

我希望它删除所有三个节点而不是第一个节点,使第二个选择返回:

id  data
1   <a id="4" />

有没有办法在单个查询中删除多个节点?具体来说,我想删除与另一个表中的列匹配条件的所有节点(在此示例中,t是动态创建的,但它可以很容易地成为实际的表)。

1 个答案:

答案 0 :(得分:3)

您可以将加入的查询中的xmlid变为逗号分隔的字符串,并在谓词中使用该字符串。

create table #IdToDelete(id int, xmlid int)
insert into #IdToDelete values (1, 1)
insert into #IdToDelete values (1, 2)
insert into #IdToDelete values (1, 3)
insert into #IdToDelete values (2, 4)

update x
set data.modify('delete //a[contains(sql:column("t.xmlid"), @id)]')
from #xmltemp x
inner join (
    select D1.id,
           (select ','+cast(D2.xmlid as varchar(10))
            from #IdToDelete as D2
            where D1.id = D2.id
            for xml path('')) as xmlid
    from #IdToDelete as D1
    group by D1.id
) t on t.id = x.id