简体   繁体   中英

Update a SQL XML Field node value for a given attribute

I have a table with the following format:

int IndexField
xml ConfigField

A ConfigField field value might look similar to

 <Parameters>
      <Parameter Type="Config" Name="Prefix">hd</Parameter>
      <Parameter Type="Config" Name="PgNumber">2</Parameter>
      <Parameter Type="Config" Name="IsValid">False</Parameter>
    </Parameters>

I would like to know the SQL Server syntax to modifythe Parameters XML node for the PgNumber value from 2 to 3 where IndexField = 22

Thanks

You can use function modify() and correct XQuery to set the value that you need. The syntax is quite tricky though. In your case you should be able to use such query:

UPDATE YourTableName
SET ConfigField.modify('replace value of (/Parameters/Pararameter[@Name="PgNumber"]/text())[1] with "3"')
WHERE IndexField = 22

This is one possible XQuery expression to be passed to the SQL Server's modify() method for updating value of <Parameter Name='PgNumber'> element :

UPDATE MyTable
SET ConfigField.modify('
        replace value of 
            (/Parameters/Parameter[@Name="PgNumber"]/text())[1] 
        with 3
    ')
WHERE IndexField = 22

Sqlfiddle Demo

Notice that in XPath/XQuery you need to put @ at the beginning of attribute name to reference an XML attribute.

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