2

I have a XML Column in My Table. The XML Structure is something like this:

   <Nodes>
    <Node>
     <Name>a</Name>
    </Node>
    <Node>
     <Name>a</Name>
    </Node>
   </Nodes>

I am trying to insert in both the nodes: I tried this:

  SET @xml.modify('       
    insert <Phone>111</Phone> 
   into (/Nodes/Node)[1]') 

But this inserts Phone in just first occurrence.

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
user2561997
  • 443
  • 1
  • 6
  • 18

1 Answers1

2

unfortunately, you cannot update multiple nodes inside xml, you can use loop:

select @i = @xml.value('count(Nodes/Node)', 'int')

while @i > 0
begin
   set @xml.modify('insert <Phone>111</Phone> into (/Nodes/Node)[sql:variable("@i")][1]') 

   set @i = @i - 1
end

select @xml

or you can reconstruct your xml like this:

select
    111 as Phone,
    t.c.value('Name[1]', 'nvarchar(max)') as Name
from @xml.nodes('Nodes/Node') as t(c)
for xml path('Node'), root('Nodes')

sql fiddle demo

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197