Add new xml node in specific location

Terry St Jean 81 Reputation points
2023-04-29T11:11:53.1033333+00:00

I have a table with a xml column.
I need to add a new node to the xml but it needs to go into a specific location.

Here is an example. Not our actual data but the structure is similar.
I want to add the following between Milk and Lettuce.
<Product>
<Category>Vegetable</Category>
<Name>Carrots</Name>
</Product>
Using SQL, how would I insert this. I've tried using the .modify method but can't get the syntax correct.

<Table>
   <Product>
      <Category>Dairy</Category>
      <Name>Milk</Name>
   </Product>
   <Product>
      <Category>Vegetable</Category>
      <Name>Lettuce</Name>
   </Product>
</Table>
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,826 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 111.6K Reputation points MVP
    2023-04-29T11:44:13.13+00:00
    DECLARE @x xml = '<Table>
       <Product>
          <Category>Dairy</Category>
          <Name>Milk</Name>
       </Product>
       <Product>
          <Category>Vegetable</Category>
          <Name>Lettuce</Name>
       </Product>
    </Table>'
    
    SET @x.modify('insert  <Product><Category>Vegetable</Category><Name>Carrots</Name></Product> after  (/Table/Product[Name="Milk"])[1]')
    SELECT @x
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.