简体   繁体   中英

Updating XML column - Sql Server

I have an XML column


<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

 <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.
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. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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