经过一段时间的尝试,我认为这是不可能的......
这里有类似的问题:XQuery 在单个 SQL 更新命令中添加或替换属性 https://stackoverflow.com/q/3854308/5089204
The .modify(insert Expression1 ... )
不允许获取数据within通过传入的 XML@sql:variable()
or sql:column()
阅读此处:https://msdn.microsoft.com/en-us/library/ms175466.aspx https://msdn.microsoft.com/en-us/library/ms175466.aspx在 Expression1 -> “常量 XML 或独立 sql:column / sql:variable 或 XQuery(到同一实例)
DECLARE @xml1 XML= --the existing XML
'<Products>
<Product id="1" score="1" />
<Product id="2" score="5" />
<Product id="3" score="4" />
</Products>';
DECLARE @xml2 XML= --the XML with new or changed data
'<Products>
<Product id="2" score="5" />
<Product id="3" score="2" />
<Product id="7" score="1" />
</Products>';
SET @xml1.modify('insert sql:variable("@xml2") as first into /Products[1]');
SELECT @xml1;
/* The full node is inserted!
Without any kind of preparation there is NO CHANCE to get the inner nodes only
<Products>
<Products>
<Product id="2" score="5" />
<Product id="3" score="2" />
<Product id="7" score="1" />
</Products>
<Product id="1" score="1" />
<Product id="2" score="5" />
<Product id="3" score="4" />
</Products>
*/
您可以这样声明第二个 XML:
DECLARE @xml2 XML= --the XML with new or changed data
'<Product id="2" score="5" />
<Product id="3" score="2" />
<Product id="7" score="1" />';
但是您将没有机会使用 id 的值作为 XQuery 过滤器
SET @xml1.modify('insert sql:variable("@xml2") as first into /Products[**How should one filter here?**]');
最后但并非最不重要的一点是,我认为没有机会在一次调用中组合两个不同的 XML_DML 语句.modify()
.
我唯一的想法就是这个,但行不通。好像只能用IFwithin一个表达式,但不是两个区分两个执行路径
SET @xml1.modify('if (1=1) then
insert sql:variable("@xml2") as first into /Products[1]
else
replace value of /Products[1]/Product[@id=1][1]/@score with 100');
所以我的结论是:不,这是不可能的......
我在这里提供的解决方案https://stackoverflow.com/a/35060150/5089204 https://stackoverflow.com/a/35060150/5089204在第二部分(“如果你想‘合并’两本书结构”)将是我解决这个问题的方法。