tsql how to split xml and insert them as rows

 ̄綄美尐妖づ 提交于 2021-02-08 02:13:04

问题


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!


回答1:


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)


来源:https://stackoverflow.com/questions/37658615/tsql-how-to-split-xml-and-insert-them-as-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!