1

如果您在 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 是动态创建的,但它也可以很容易地成为实际表)。

4

1 回答 1

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
于 2011-10-07T07:14:29.460 回答