2

My sample xml value looks like

    <food>
     <name>Belgian Waffles</name>
     <price>$5.95</price>
     <description>
     Two of our famous Belgian Waffles with plenty of real maple syrup
     </description>
     <calories>650</calories>
    </food>

I need to add this <Shop>KFC</Shop> into the food tag and my output should looks as

  <food>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>
    Two of our famous Belgian Waffles with plenty of real maple syrup
    </description>
    <calories>650</calories>
    <Shop>KFC</Shop>
  </food>

I tried UpdateXml but behaves differently. Is it possible with the available xml functions in MySql to do this ?

I am new to MySql. Please help me in figure out this.. Thanks in advance..

UPDATE :

I tried this code

select UpdateXML('<food>
 <name>Belgian Waffles</name>
 <price>$5.95</price>
 <description>
 Two of our famous Belgian Waffles with plenty of real maple syrup
 </description>
 <calories>650</calories>
</food>', '/food/Shop', '<Shop>KFC</Shop>');

and in the second parameter i tried instead '/food/Shop' only with '/food' but its not giving the expected results

shanmugharaj
  • 3,814
  • 7
  • 42
  • 70

1 Answers1

2

Turns out that it's a bit tricky to do in MySql. You can achieve that by replacing existing <calories> node with <calories> + new <shop> node.

Use ExtractValue() function to get value of existing <calories> and construct <calories>value</calories> block :

set @data = N'<food>
 <name>Belgian Waffles</name>
 <price>$5.95</price>
 <description>
 Two of our famous Belgian Waffles with plenty of real maple syrup
 </description>
 <calories>650</calories>
</food>';

set @data =UpdateXML(@data, 
                     '/food/calories', 
                     concat(
                        '<calories>',
                         ExtractValue(@data, '/food/calories'),
                        '</calories><Shop>KFC</Shop>'
                        )
                    );
select @data

Fiddle demo for this answer

Similar problem : MySQL to update an XML attribute

Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137