Обновление значения XML с использованием .modify на SQL сервере - PullRequest
0 голосов
/ 22 января 2020

Мы пытаемся обновить значение для isEnabled (в True) в столбце xml. Мы пробовали разные способы обновления, следуя аналогичным вопросам, заданным ранее в SO, и не увенчались успехом.

Ниже приведена ссылка SQLFiddle .

http://sqlfiddle.com/#! 18 / d48ba8 / 7/0

Любая помощь приветствуется.

- XML data

   <Communication>
   <EventTypes>
   <EventType>
    <IsEnabled>false</IsEnabled>
    <Name>HK</Name> 
  </EventType>
  </EventTypes>
  </Communication>
  </ReimbursementProfile>

--Script to Update
UPDATE 
   Table2
SET 
   XMLCol.modify('replace value of (/ReimbursementProfile/Communication/EventTypes/EventType/IsEnabled/text())[1] with ("true")')

WHERE
   ID = 1

[![Actual Stucture of the XML File][1]][1]


  [1]: https://i.stack.imgur.com/BrOhd.png

Additional where condition for updating the actual XML value 
WHERE ProfileId =21599  and XmlValue.value('(/ReimbursementProfile/Communication/EventTypes/EventType/Name)[1]', 'nvarchar(max)') = 'Trip Log Entry Reminder' 

Ответы [ 2 ]

0 голосов
/ 30 января 2020

Обновление работает нормально, как предложено @marc_s, обновление не было выполнено из-за пространства имен. После явного упоминания пространства имен обновление работает нормально, к сожалению, мы не можем использовать точное пространство имен.

Обновленный код приведен ниже.

with xmlnamespaces(default '<URLOfNameSpace>')
 UPDATE 
 ProfileXmlValues
SET 
   XmlValue.modify('replace value of (/ReimbursementProfile/Communication/EventTypes/EventType[Id=102]/IsEnabled[. != "true"]/text())[1] with ("true")')
WHERE

and XmlValue.exist ('/ReimbursementProfile/Communication/EventTypes/EventType[Id=102]/IsEnabled[. != "true"]')  = 1; 
0 голосов
/ 22 января 2020

Следующее будет обновлять элемент IsEnabled первого EventType с Name = "Trip Log ...":

create table #Table2
(
  ID int identity primary key,
  ProfileId int,
  XMLCol xml
);

insert into #Table2 (ProfileId, XMLCol)
values
(21599 , N'
<ReimbursementProfile xmlns:xsi="http://www.testxmlupdate.com">
<Communication>
<EventTypes>

    <EventType>
    <IsEnabled>false</IsEnabled>
    <Name>HK</Name> 
    </EventType>

    <EventType> <!-- this is the first EventType with Name: Trip Log..., this will get updated/replaced modify[1]-->
    <IsEnabled>false</IsEnabled>   
    <Name>Trip Log Entry Reminder</Name> 
    </EventType>

    <EventType> <!-- this is the second EventType with Name: Trip Log..., this will NOT get updated, modify(replace on singletons) -->
    <IsEnabled>false</IsEnabled>
    <Name>Trip Log Entry Reminder</Name> 
    </EventType>

    <EventType>
    <IsEnabled>false</IsEnabled>
    <Name>HK</Name> 
    </EventType>

</EventTypes>
</Communication>
</ReimbursementProfile>
');


select 'before the update', *
from #Table2;


UPDATE 
   #Table2
SET 
   XMLCol.modify('replace value of (/ReimbursementProfile/Communication/EventTypes/EventType[Name="Trip Log Entry Reminder"]/IsEnabled/text())[1] with ("true")')
WHERE
   ProfileId = 21599
and XMLCol.exist ('/ReimbursementProfile/Communication/EventTypes/EventType[Name="Trip Log Entry Reminder"]') /* ...append:  /IsEnabled[. != "true"] ..?? */  = 1;

select 'after the update', *
from #Table2;


--clean-up
drop table #Table2;
...