2

In the query below I’m updating a value in an xml node in the Items column in table X in the database. Right now I’m filtering based only on the Name attribute. Because there are multiple nodes with the same Name I need to be able to filter on more attributes during the update.

UPDATE dbo.Declarations
    SET Items.modify('replace value of 
 (/Items/Item[@Name=(sql:variable("@ItemName"))]/text())[1] 
 with sql:variable("@Value")')
   WHERE DeclarationId = @DeclarationId
END

Is it possible to select an XML node based on multiple attribute values and then update the value of this node?

4

2 回答 2

3

You can use and in the predicate and add more checks.

declare @X xml = '
<Items>
  <Item Name = "Name1" Type = "Type1">Value1</Item>
  <Item Name = "Name2" Type = "Type2">Value2</Item>
</Items>
'

declare @Value varchar(10) = 'NewValue2'
declare @Name varchar(10) = 'Name2'
declare @Type varchar(10) = 'Type2'

set @X.modify('
  replace value of (/Items/Item[
                               @Name = sql:variable("@Name") and 
                               @Type = sql:variable("@Type")
                               ]/text())[1]
  with sql:variable("@Value")
')
于 2013-10-01T16:32:48.430 回答
0
UPDATE dbo.Declarations
    SET Items.modify('replace value of 
 (/Items/Item[@Name=(sql:variable("@ItemName"))][@Attr=(sql:variable("@newParam"))]/text())[1] 
 with sql:variable("@Value")')
   WHERE DeclarationId = @DeclarationId
END

Should do it; assuming that you have an attribute named Attr and a new sql variable of @newParam.

于 2013-10-01T16:29:44.717 回答