I would like to update a piece of xml, which I hold in an variable. I would like to update the value of Value
where Name
is a given value. Here's a mockup of the xml:
<ParameterValues>
<ParameterValue>
<Name>TO</Name>
<Value>me@you.com</Value>
</ParameterValue>
<ParameterValue>
<Name>CC</Name>
<Value>bob@email.com</Value>
</ParameterValue>
<ParameterValue>
<Name>Priority</Name>
<Value>NORMAL</Value>
</ParameterValue>
</ParameterValues>
I have written the below, which always updates the first value, but I'd like to change the modify
command so that I have the equivalent to a where clause - I would like to update (for instance) the value where Name = "CC"
in the same node. How do I achieve this?
All the examples I see online assume I have a unique identifier for each node in the tree structure above the value I want to update, not at the same level.
DECLARE @Email VARCHAR(50) = 'New@email.co.uk';
DECLARE @Ext XML =
'<ParameterValues>
<ParameterValue>
<Name>TO</Name>
<Value>me@you.com</Value>
</ParameterValue>
<ParameterValue>
<Name>CC</Name>
<Value>bob@email.com</Value>
</ParameterValue>
<ParameterValue>
<Name>Priority</Name>
<Value>NORMAL</Value>
</ParameterValue>
</ParameterValues>';
SET @Ext.modify('replace value of (//Value/text())[1] with sql:variable("@Email")');
SELECT
Col.value('./Name[1]','VARCHAR(100)') AS [Name]
,Col.value('./Value[1]','VARCHAR(1000)')AS [Value]
FROM
@Ext.nodes('//ParameterValue') AS Tab(Col);
All help gratefully received!