I have three tables table1, table2, table3 with col1, col2 and identity ID column. These table relationship are defined in the database.
I am trying to create a stored procedure that accepts xml string input and save that data into tables.
This is the XML input
<root>
<table1 col1='a' col2='b'>
<table2Array>
<table2 col1='c' col2='d'>
<table3array>
<table3 col1='g' col2='h' />
<table3 col1='i' col2='j' />
</table3array>
</table2>
<table2 col1='c' col2='d'>
<table3array>
<table3 col1='k' col2='l' />
<table3 col1='i' col2='j' />
</table3array>
</table2>
</table2Array>
</table1>
<table1 col1='a' col2='b'>
<table2Array>
<table2 col1='e' col2='f'>
<table3array>
<table3 col1='i' col2='j' />
<table3 col1='i' col2='j' />
</table3array>
</table2>
<table2 col1='e' col2='f'>
<table3array>
<table3 col1='g' col2='h' />
<table3 col1='g' col2='h' />
</table3array>
</table2>
</table2Array>
</table1>
</root>
This xml is coming from a third party object and we don’t have control to modify the third party object to emit a different format xml.
Algorithm:
- Loop through each node
- Insert node attribute into table
- Get last identity value
- Call child nodes with last identity value as foreign key
- Do until no more child nodes
Is this the only way to handle this situation? If so how to iterate through xml node?
Please help!!
Thanks,
Esen
Using merge and
outputyou can do this without a loop using a technique described here.I assume your table structure is like this.
The code
SE-Data (select "Text-only results" to see all resultsets)