Dynamically replacing the value of a node in XML DML

不问归期 提交于 2019-12-10 20:08:24

问题


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>

回答1:


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")')


来源:https://stackoverflow.com/questions/15435485/dynamically-replacing-the-value-of-a-node-in-xml-dml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!