I have a scalar xml variable:
DECLARED @XML xml =
'<rows>
<row>
<column1 attrib="" />
<column2 attrib="" />
</row>
<!-- ... -->
</rows>';
I would like to split the data so that each row’s xml is assigned to a new record in a table:
Id | ... | XML
1 | | '<row><column1 attrib="" /><column2 attrib="" /></row>'
2 | | etc.
3 | | etc.
I haven’t quite grasped xquery so I’m having trouble writing an insert statement that does what I want.
INSERT into MyTable( [XML])
SELECT @XML.query('row')
Now I know something is happening but it appears rather than doing what I intended and inserting multiple new records it is inserting a single record with an empty string into the [XML] column.
What am I not getting?
Clarification
I am not trying to get the inner text, subelements or attributes from each row using value(...). I am trying to capture the entire <row> element and save it to a column of type xml
I’ve experimented with nodes(...) and come up with:
INSERT into MyTable([XML])
SELECT C.query('*')
FROM @XML.nodes('rows/row') T(C)
Which is closer to what I want but the results don’t include the outer <row> tag, just the <column*> elements it contains.
T-SQL Script:
Results: