简体   繁体   English

SQL,查找xml变量中的节点值(如果存在)将其他节点插入xml变量中

[英]SQL, Find node value in xml variable, if it exists insert additional nodes into xml variable

I've got a Stored Procedure in SQL, where I have the following declaration: 我在SQL中有一个存储过程,我有以下声明:

Declare @fields xml 声明@fields xml

My SP gets passed values from the front end and then gets executed. 我的SP从前端传递值然后执行。 The values it gets passed looks like this depending on what the user selects from the front end. 它传递的值看起来像这样取决于用户从前端选择的内容。 For the purpose of this example I have included only 3 ID's. 出于这个例子的目的,我只包括3个ID。

'<F><ID>979</ID><ID>1000</ID><ID>989</ID></F>'

My question is this: 我的问题是:

How can I find the node = 1000 and if that is present (exists) then insert (add) to 2 additional nodes, 如何找到node = 1000以及是否存在(存在),然后插入(添加)到另外2个节点,

<ID>992</ID><ID>993</ID>

to my existing '<F><ID>979</ID><ID>1000</ID><ID>989</ID></F>' xml. 到我现有的'<F><ID>979</ID><ID>1000</ID><ID>989</ID></F>' xml。

If <ID>1000</ID> isn't present do nothing. 如果<ID>1000</ID>不存在则不执行任何操作。

So, end result should be something like this if 1000 is present. 所以,如果1000存在,最终结果应该是这样的。

<F><ID>979</ID><ID>1000</ID><ID>989</ID><ID>992</ID><ID>993</ID></F>

If not, the result should stay: 如果没有,结果应保持:

<F><ID>979</ID><ID>1000</ID><ID>989</ID></F>

I just can't get my head around this? 我只是无法理解这个?

Check this: 检查一下:

declare @fields xml = '<F><ID>979</ID><ID>1000</ID><ID>989</ID></F>'
    , @add xml = '<ID>992</ID><ID>993</ID>'
;
if @fields.exist('/F[1]/ID[text()="1000"]') = 1
    set @fields.modify('insert sql:variable("@add") as last into /F[1]');

select @fields

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM