I am trying to update XML string, but I am getting this error:
Incorrect use of the XML data type method 'modify'. A non-mutator method is expected in this context
Code:
DECLARE @xmlVal XML ='<r k="ABC"><p k="Id">721</p><p k="ConnectionId">17150E3C-2D3B-4760-B392-0DF7563198D1</p><l k="param" /><l k="filter"><l k="Default"><p k="Id">123</p><l k="Exclude"><l k="Exe"><p k="__Id">efbef694-e86f-487b-9360-9596224c9908</p><l k="Criteria" /></l></l><p k="Family"></p></l></l><l k="Methods" /><l k="Groups" /><p k="Default"></p></r>'
SELECT
CAST(@xmlVal.modify('replace r/p/p/text())[1] WITH 2BDFF1B4-33CD-4CF9-9AD6-17F28C2F03E0') AS varchar(max))
Please let me know what I am doing wrong to replace text inside p
tab with k=ConnectionId
It is impossible to modify XML via XQuery .Modify()
method inside a SELECT
statement. It should be two distinct statements.
SQL
DECLARE @xmlVal XML =
N'<r k="ABC">
<p k="Id">721</p>
<p k="ConnectionId">17150E3C-2D3B-4760-B392-0DF7563198D1</p>
<l k="param"/>
<l k="filter">
<l k="Default">
<p k="Id">123</p>
<l k="Exclude">
<l k="Exe">
<p k="__Id">efbef694-e86f-487b-9360-9596224c9908</p>
<l k="Criteria"/>
</l>
</l>
<p k="Family"></p>
</l>
</l>
<l k="Methods"/>
<l k="Groups"/>
<p k="Default"></p>
</r>';
DECLARE @d UNIQUEIDENTIFIER = '2BDFF1B4-33CD-4CF9-9AD6-17F28C2F03E0';
SET @xmlVal.modify('replace value of
(r/p[@k="ConnectionId"]/text())[1]
with sql:variable("@d")');
-- test
SELECT @xmlVal;
Output
<r k="ABC">
<p k="Id">721</p>
<p k="ConnectionId">2BDFF1B4-33CD-4CF9-9AD6-17F28C2F03E0</p>
<l k="param" />
<l k="filter">
<l k="Default">
<p k="Id">123</p>
<l k="Exclude">
<l k="Exe">
<p k="__Id">efbef694-e86f-487b-9360-9596224c9908</p>
<l k="Criteria" />
</l>
</l>
<p k="Family" />
</l>
</l>
<l k="Methods" />
<l k="Groups" />
<p k="Default" />
</r>