Search code examples
sqlxmlsql-server-2012xquerysqlxml

sql xquery to add xml block into specific position


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]')

Solution

  • 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]
    ')