1

I am looking for a way to insert a specific XML node in a specific location. Below is the example:

<Car>
     <Brand>Toyota</Brand>
     <Color>Red</Color>
     <Price>10000</Color>
</Car>

Say if I were to want to insert a node <Year>2012</Year> in between <Color> and <Price> node, what should I do?

Do note that replacing whole XML doc is not an option in my current scenario. Thanks

4
  • See: stackoverflow.com/questions/3004670/… Commented Aug 15, 2016 at 2:52
  • @NoChance Hi, was looking for away to do it through T-SQL directly instead. Any idea? Thanks Commented Aug 15, 2016 at 2:54
  • Sorry, no idea about that. Commented Aug 15, 2016 at 3:29
  • What flavor of SQL? SQL Server, Oracle, MySQL, Postgre, or something else? Commented Aug 15, 2016 at 4:44

1 Answer 1

5

You can use XQuery insert ... after ... statement to insert Year element right after Color :

declare @xml XML = '<Car>
     <Brand>Toyota</Brand>
     <Color>Red</Color>
     <Price>10000</Price>
</Car>'

SET @xml.modify('
    insert <Year>2012</Year>
    after (//Color)[1]
')

SELECT @xml

output :

<Car>
  <Brand>Toyota</Brand>
  <Color>Red</Color>
  <Year>2012</Year>
  <Price>10000</Price>
</Car>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.