简体   繁体   中英

With SQL Server XML data type, how to update the value attribute when searching with another attribute to locate the xml node?

I have a XML column in my table that stores a XML structure like this:

<cars>
    <car name="Ford" value="123" />
    <car name="Honda" value="456" />
</cars>

I want to modify all rows that have name="Honda" and value="456". I need to update the number 456 to 789.

I tried this:

UPDATE cars
SET XmlData.modify('replace value of (/cars/car[@name="Honda"]/value) with "789"')
WHERE isProcessed = 0

I am getting the error:

Msg 2261, Level 16, State 1, Line 41
XQuery Cars.XmlData.modify()]: There is no element named 'value' in the type 'element(car,#anonymous) *'.

You were so close... Just missed .../@value)[1]

Example

Declare @Cars table (ID int,IsProcessed bit,XMLData xml)
Insert Into @Cars values
(1,0,'<cars><car name="Ford" value="123" /><car name="Honda" value="456" /></cars>')

Update @Cars
 Set   XMLData.modify('replace value of (/cars/car[@name="Honda"]/@value)[1]  with "789"')
 WHERE isProcessed = 0

Select * from @Cars

The Updated XML

<cars>
  <car name="Ford" value="123" />
  <car name="Honda" value="789" />
</cars>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM