Sql server 在SQL 2005中使用XML.modify()在多个XML节点中插入属性
我有一个从单个select语句创建的@XML文档Sql server 在SQL 2005中使用XML.modify()在多个XML节点中插入属性,sql-server,xml,sql-server-2005,xml-dml,Sql Server,Xml,Sql Server 2005,Xml Dml,我有一个从单个select语句创建的@XML文档 <root> <node> <node1> <targetNode> </targetNode> </node1> <node1> <targetNode> </targetNode> </node1> <node1> <targetNode> &
<root>
<node>
<node1>
<targetNode>
</targetNode>
</node1>
<node1>
<targetNode>
</targetNode>
</node1>
<node1>
<targetNode>
</targetNode>
</node1>
</node>
<node>
......
</node>
</root>
上面将把属性插入@XML文档中targetNode的第一个实例中。但是,insert语句只能在单个节点上工作。是否有任何方法可以将此属性插入@XML文档中targetNode的所有实例。这是使用modify函数无法实现的。它只在单个节点上工作
@XML.modify( 'insert attribute xsi:nil {"true"} into (root/node/node1/targetNode) [1]')
您可以将其作为字符串进行操作,尽管这肯定很难看,而且在某些情况下可能是错误的,这取决于XML的实际结构
像这样:
declare @xml as xml
set @xml = '<root>
<node>
<node1>
<targetNode>
</targetNode>
</node1>
<node1>
<targetNode>
</targetNode>
</node1>
<node1>
<targetNode>
</targetNode>
</node1>
</node>
</root>
'
set @xml = replace(cast(@xml as nvarchar(max)), '<targetNode/>', '<targetNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />')
select @xml
将@xml声明为xml
set@xml=
'
设置@xml=replace(强制转换(@xml为nvarchar(max)),“”,)
选择@xml
您可以在用于创建xml的select中使用XSINILL参数执行此操作
(这是一个非常粗略的例子)
我在多个节点上的DML操作中找到了一个简单而优雅的解决方案 这样做的目的是计算有多少个节点并逐个修改它们:
DECLARE @iCount int
SET @iCount = @var.value('count(root/node/node1/targetNode)','int')
DECLARE @i int
SET @i = 1
WHILE (@i <= @iCount)
BEGIN
@xml.modify('insert attribute xsi:nil {"true"} into (root/node/node1/targetNode)[sql:variable("@i")][1]')
SET @i = @i + 1
END
DECLARE@iCount int
设置@iCount=@var.value('count(root/node/node1/targetNode)','int')
声明@i int
设置@i=1
而(@i
DECLARE @iCount int
SET @iCount = @var.value('count(root/node/node1/targetNode)','int')
DECLARE @i int
SET @i = 1
WHILE (@i <= @iCount)
BEGIN
@xml.modify('insert attribute xsi:nil {"true"} into (root/node/node1/targetNode)[sql:variable("@i")][1]')
SET @i = @i + 1
END