Reputation: 449
There was a question here (How to update all xml attributes' value in an xml variable using t-sql?) where the questioner wanted to split an xml variable into rows.
I have almost the same problem, but I'm storing the xmls in a table. Every row stores at least 1 xml node, sometimes more. I want to split them to separate rows, but it seems like .nodes('a') needs a scalar variable.
This is what I've tried:
declare @T table (XMLCol xml);
insert into @T values
('<a abb="122">
<b></b>
</a>
<a abb="144">
<b></b>
</a>'),
('<a abb="222">
<b></b>
</a>
<a abb="244">
<b></b>
</a>');
select a.query('.') from @T.nodes('a') a(a);
What I want to achieve: I have a table like this:
ID XML
1 <a abb="122"><b></b></a><a abb="144"><b></b></a>
2 <a abb="222"><b></b></a><a abb="244"><b></b></a>
I want to convert it to something like that:
ID XML
1 <a abb="122"><b></b></a>
2 <a abb="144"><b></b></a>
3 <a abb="222"><b></b></a>
4 <a abb="244"><b></b></a>
For that I want to write something that works like a simple
INSERT INTO table2 SELECT * FROM table1
Can you help me please?
Thanks in advance!
Upvotes: 2
Views: 5199
Reputation: 2800
Try like this (if I understood your question correctly):
declare @xml xml = N'<a abb="122"><b></b></a><a abb="144"><b></b></a>'
select @xml.query('/a/*')
If you want each b node to be shown as row, use this:
select x.items.query('.') from @xml.nodes('/a/b') as x(items)
Edit: You can get data from your table variable like this:
select tbl.vals
from @T as t
cross apply (select x.items.query('.') from t.XMLCol.nodes('/a') as x(items)) as tbl(vals)
Upvotes: 7