sql xquery to add xml block into specific position
Asked Answered
S

1

1

Using sql server 2012 sp1 I haven't been able to find a solution out there but I believe that its not possible to add xml block into specific position of an existing xml column in a table. For example say we had tbTable.AnimalsXML which is:

<Animals>
  <Animal name="Dog">
    <Enclosure id="Default">
      <Value>xyz</Value>
    </Enclosure>
  </Animal>
  <Animal name="Cat">
    <Enclosure id="Default">
      <Value>xyz</Value>
    </Enclosure>
  </Animal>
  <Animal name="Bird">
    <Enclosure id="Default">
      <Value>xyz</Value>
    </Enclosure>
  </Animal>
  <Animal name="Sheep">
    <Enclosure id="Default">
      <Value>xyz</Value>
    </Enclosure>
  </Animal>
</Animals>

How does one insert:

<Animal name="Goat">
    <Enclosure id="Default">
      <Value>xyz</Value>
    </Enclosure>
</Animal>

in between Cat and Bird blocks?

Tried position() and found this problem, how do we get it done in sql using:

update tbTable set AnimalsXML.modify('
            insert
                sql:variable("@var")
            as "specific position"
            into (/Animals)[1]')
Smarten answered 14/3, 2016 at 3:27 Comment(0)
K
3

You can use insert ... after ... construct to insert new element after certain existing element. Example below inserts new element after the existing <Animal name="Cat"> element :

declare @data XML = '<Animals>
  <Animal name="Dog">
    <Enclosure id="Default">
      <Value>xyz</Value>
    </Enclosure>
  </Animal>
  <Animal name="Cat">
    <Enclosure id="Default">
      <Value>xyz</Value>
    </Enclosure>
  </Animal>
  <Animal name="Bird">
    <Enclosure id="Default">
      <Value>xyz</Value>
    </Enclosure>
  </Animal>
  <Animal name="Sheep">
    <Enclosure id="Default">
      <Value>xyz</Value>
    </Enclosure>
  </Animal>
</Animals>'

set @data.modify('
insert 
    <Animal name="Goat">
        <Enclosure id="Default">
          <Value>xyz</Value>
        </Enclosure>
    </Animal>
after (/Animals/Animal[@name="Cat"])[1]
')
Koloski answered 14/3, 2016 at 3:54 Comment(1)
awww thanks, I was using first & last and getting nowhere, but didn't know about before & after as per [link]msdn.microsoft.com/en-AU/library/ms175466.aspxSmarten

© 2022 - 2024 — McMap. All rights reserved.