简体   繁体   English

更新XML列-SQL Server

[英]Updating XML column - Sql Server

I have an XML column 我有一个XML栏
setting 设置


<root>
  <Tag1>true</Tag1>
  <Tag2>
    <Tag3>
      <Tag4>43</Tag4>
      <Tag4>44</Tag4>
      <Tag4>46</Tag4>
      <Tag4>50</Tag4>
      <Tag4>89</Tag4>
      <Tag4>99</Tag4>
      <Tag4>166</Tag4>
    </Tag3>
  </Tag2>
</root>

I actually need to update the above above column to insert the below sub braches into Tag3 branch, only if they don't exist in the column and also where Tag1 is true 实际上,我需要更新以上的上一列,以将以下子分支插入Tag3分支中,仅当它们不在该列中且Tag1为true时

 <Tag4>43</Tag4>
 <Tag4>44</Tag4>
 <Tag4>46</Tag4>
 <Tag4>165</Tag4>

I have this to select where Tag1 is true but a little confused with updating the Tag3 branch with Tag4 subbranches inserted only if they dont exist in Tag3. 我可以选择Tag1为true的地方,但与Tag3子分支(仅在Tag3中不存在它们的情况下)更新Tag3分支时有些困惑。
SELECT * from table WHERE Setting.exist('//Tag1[text() = "true"]') = 1

In my above example I want only <Tag4>165</Tag4> should be inserted into the column and the final output should be something like this. 在上面的示例中,我只希望将<Tag4>165</Tag4>插入列中,并且最终输出应该是这样的。 Any help is greatly appreciated!! 任何帮助是极大的赞赏!!

<root>
  <Tag1>true</Tag1>
  <Tag2>
    <Tag3>
      <Tag4>43</Tag4>
      <Tag4>44</Tag4>
      <Tag4>46</Tag4>
      <Tag4>50</Tag4>
      <Tag4>89</Tag4>
      <Tag4>99</Tag4>
      <Tag4>165</Tag4>
      <Tag4>166</Tag4>
    </Tag3>
  </Tag2>
</root>

The below inserts the elements that don't exist, but not in order. 下面插入了不存在但不按顺序排列的元素。 Maybe it will help. 也许会有所帮助。

DECLARE @x1 XML = 
'<root>
  <Tag1>true</Tag1>
  <Tag2>
    <Tag3>
      <Tag4>43</Tag4>
      <Tag4>44</Tag4>
      <Tag4>46</Tag4>
      <Tag4>50</Tag4>
      <Tag4>89</Tag4>
      <Tag4>99</Tag4>
      <Tag4>166</Tag4>
    </Tag3>
  </Tag2>
</root>'
, @x2 XML = 
'<Tag4>43</Tag4>
 <Tag4>44</Tag4>
 <Tag4>46</Tag4>
 <Tag4>165</Tag4>';

DECLARE @x3 XML = (
    SELECT  * 
    FROM (
        SELECT  s.n.value('.','int') FROM @x2.nodes('*') AS s(n)
        EXCEPT
        SELECT  f.n.value('.','int') 
        FROM    @x1.nodes('/root/Tag2/Tag3/Tag4') AS f(n)
    ) AS Tag4Values (Tag4)
    FOR XML PATH (''));

SET @x1.modify('insert sql:variable("@x3") into (/root/Tag2/Tag3)[1]');

SELECT @x1;

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

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