我有:
- 具有 xml 类型列(ID 列表)的表
- xml 类型参数(也是 ID 列表)
从列中删除与参数中的节点匹配的节点,同时保持任何不匹配的节点不变的最佳方法是什么?
例如
declare @table table (
[column] xml
)
insert @table ([column]) values ('<r><i>1</i><i>2</i><i>3</i></r>')
declare @parameter xml
set @parameter = '<r><i>1</i><i>2</i></r>'
-- this is the problem
update @table set [column].modify('delete (//i *where text() matches @parameter*)')
MSDN 文档表明它应该是可能的(在 Introduction to XQuery in SQL Server 2005 中):
This stored procedure can easily be modified to accept an XML fragment which contains one or more skill elements thereby allowing the user to delete multiple skill nodes with a single invocation of stored procedure.
最佳答案
虽然以这种方式删除有点笨拙,但如果您的数据很简单(例如您给出的示例),您可以改用更新来更改数据。下面的查询基本上将两个 XML 字符串拆分成表,连接它们,排除非空(匹配)值,并将其转换回 XML:
UPDATE @table
SET [column] = (
SELECT p.i.value('.','int') AS c
FROM [column].nodes('//i') AS p(i)
OUTER APPLY (
SELECT x.i.value('.','bigint') AS i
FROM @parameter.nodes('//i') AS x(i)
WHERE p.i.value('.','bigint') = x.i.value('.','int')
) a
WHERE a.i IS NULL
FOR XML PATH(''), TYPE
)
关于sql-server - 在 SQL Server 的单个 XQuery 中删除多个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1020305/