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?

2 Answers 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")
')
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.