Is there a way to write a new subtree to an XML node in SQL, specifically for a dynamic query? I know it's possible using some combination of insert and delete statements, but I'm looking for something that works in a fairly implicit way. IE, I don't want to have to write a different query for each specific case that this is needed. So for example, say I have this XML hierarchy:
<root>
...
<node>
<node1>
...
</node1>
<node2>
...
</node2>
...
</node>
...
</root>
If I want to replace the value of a single node, I have this query:
DECLARE @newVal varchar(max)
DECLARE @XPath varchar(max)
SELECT @newVal = 'newValue'
SELECT @XPath = 'root/node/node1/text()'
DECLARE @query varchar(max)
SET @query = '
UPDATE [dbo].[Users]
SET [NewSettingsXml].modify(''
replace value of (' + @XPath + ')[1]
with "' + @newVal + '"'')'
exec(@query)
I was hoping that I would just be able to do something like @newVal = '<newNode>foo</newNode>', where the new XML would come from a serialized C# object, but, not surprisingly, it encodes the value into text, setting it as <newNode>foo</newNode> instead. Is there a way to do this in a similar fashion?