Quick one today:
Continuing the series of posts on XML DML, today, we’ll look at updating/replacing value in an non-existing node (or INSERTing a new node into an existing element).
In the past two posts, we saw how to update (or replace ) values in XML nodes.
- The first one is about updating value in a simple untyped XML updates.
- Second one has two sections:
- Update (or replace) element attribute value in a typed XML. See the code under section ‘Side story for context : Update Attribute value‘
- Update node value of typed XML section
- Third one is about updating value in an empty node.
Today, we’ll see how to update a non-existing node or INSERTing a new node into an existing element.
Let’s use the same code as before to set the stage:
-- -- Create new sample table -- CREATE TABLE dbo.SampleXML ( ID INT NOT NULL IDENTITY(1,1) , XML_Col XML ) GO -- -- Create XML value -- DECLARE @X XML = ' <Root> <ParentElement Att1="Color" Att2="10"> <Child1>Marco</Child1> <Child2>Polo</Child2> </ParentElement> <ParentElement Att1="Brand" Att2="16"> <Child1>Hello</Child1> <Child2></Child2> </ParentElement> <ParentElement Att1="Style" Att2="8"> <Child1>Hello</Child1> </ParentElement> </Root>' -- -- INSERT XML value into table column -- INSERT INTO dbo.SampleXML (XML_Col) VALUES (@X) GO -- -- See the result -- SELECT * FROM dbo.SampleXML GO
Sample XML file looks like this:
Lets try to update the section in red in the image above.
Update non-existing Node or INSERT a new node into existing element
As it is obvious by now, that updating value of an non-existing node in an element is same as INSERTing a new node. The reason, non-existing aspect is highlighted is because, this XML example has multiple <ParentElement> elements, that have similar structure.
- First ParentElement has all two nodes with values
- Second element only has data in first node; Second child node is empty.
- Third element also only has data in first node; Second child node does not exist.
In this example, lets work on the third scenario:
-- -- INSERT new node -- UPDATE dbo.SampleXML SET XML_Col.modify(' insert <Child2>Contemporary<Child2> into (/Root/ParentElement[@Att1="Style"])[1] ') WHERE XML_Col.exist('/Root/ParentElement[@Att1="Style"]/Child2/text()') = 0
Hope this helps,
_Sqltimes