I have the following XML data and the Element table.
DECLARE @input XML = '<root>
<C1>
<C2>
<C3> <C4>data1</C4> </C3>
</C2>
<C2>
<C3>data2</C3>
</C2>
</C1>
<D1>
<D2>data3</D2>
<D2>data4</D2>
</D1>
</root>'
Element table:( this is just an example so can be changed to match an appropriate solution.)
CREATE TABLE Element ( elementId INT IDENTITY PRIMARY KEY,
elementName VARCHAR (200) NOT NULL,
parentId INT,
data VARCHAR(300) );
According to @input the root element is parent of C1 and D1, then C1 is C2 parent, ...
What is the solution for SQL server 2012/2014 to code a stored procedure with CTE (or any other type of SQL object) to recursively put all element names into the Element table?
data column fills with data in this case, the C4 and the second C3, and D2 elements have data the rest of element are null.
I also saw Hierarchical Data type and I wonder if that could be helpful to solve this problem?
With OpenXML you can get a table representation of your XML with
ID
andParentID
columns using the metaproperties.Using the XML query in a merge will allow you to create a mapping table between the
elementId
identity column and the DOM node id from the XML.The last step is to use the mapping table to update
parentId
inElement
.SQL Fiddle
MS SQL Server 2008 Schema Setup:
Query 1:
Results: