I am struggling with this now: How do you replace the value of a node in an untyped XML column where the text is equal to a certain variable value? Is it possible?
My XML:
<attrs>
<attr>ManualInsert</attr>
<attr>ManualInsert2</attr>
<attr>ManualInsert4</attr>
<attr>ManualInsert8</attr>
</attrs>
My Tries:
DECLARE @OldValue Varchar(255) = 'ManualInsert'
DECLARE @NewValue Varchar(255) = 'ReplacedValue'
UPDATE
Labels
SET
Attributes.modify('replace value of (/attrs/attr/text())[1]
with
if ((/attrs/attr/text() = sql:variable("@OldValue")))
then sql:variable("@NewValue")
else () ')
WHERE
Id = 2000046
message: (0 row(s) affected)
DECLARE @OldValue Varchar(255) = 'ManualInsert'
DECLARE @NewValue Varchar(255) = 'ReplacedValue'
UPDATE
Labels
SET
Attributes.modify('replace value of (/attrs/attr[text() = sql:variable("@OldValue")])[1]
with sql:variable("@NewValue")')
WHERE
Id = 2000046
message:
Msg 2356, Level 16, State 1, Line 7
XQuery [Labels.Attributes.modify()]: The target of 'replace value of' must be a non-metadata attribute or an element with simple typed content, found 'element(attr,xdt:untyped) ?'
expected result:
<attrs>
<attr>ReplacedValue</attr>
<attr>ManualInsert2</attr>
<attr>ManualInsert4</attr>
<attr>ManualInsert8</attr>
</attrs>
modify('replace value of (/attrs/attr[. = sql:variable("@OldValue")]/text())[1]
with sql:variable("@NewValue")')
Your second attempt is actually just missing to specify that it is the text() that should be replaced. This will also work.
modify('replace value of (/attrs/attr[text() = sql:variable("@OldValue")]/text())[1]
with sql:variable("@NewValue")')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With