Вопрос

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.

Это было полезно?

Решение

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top