我使用the instructions from the 1st answer here试图在SQL Server 2012表中切碎一些XML,如下所示:
表A
+------+--------+
| ID | ColXML |
+------+--------+
| 0001 | <xml1> |
| 0002 | <xml2> |
| ... | ... |
+------+--------+
xml1看起来像这样:
<Attributes>
<Attribute name="address1">301 Main St</Attribute>
<Attribute name="city">Austin</Attribute>
</Attributes>
xml2看起来像这样:
<Attributes>
<Attribute name="address1">501 State St</Attribute>
<Attribute name="address2">Suite 301</Attribute>
<Attribute name="state">Texas</Attribute>
</Attributes>
任何给定的行中都有不同数量的属性。
我正在尝试将其整理成如下所示的关系表:
+------+--------------+-----------+--------+-------+
| ID | address1 | address2 | city | state |
+------+--------------+-----------+--------+-------+
| 0001 | 301 Main St | NULL | Austin | NULL |
| 0002 | 501 State St | Suite 301 | NULL | Texas |
+------+--------------+-----------+--------+-------+
这是我尝试过的代码,它返回表#T中的0行:
select dense_rank() over(order by ID,I.N) as ID,F.N.value('(*:Name/text())[1]','varchar(max)') as Name,F.N.value('(*:Values/text())[1]','varchar(max)') as Value
into #T
from TableA as T
cross apply T.Attributes.nodes('/ColXML') as I(N)
cross apply I.N.nodes('ColXML') as F(N);
declare @SQL nvarchar(max)
declare @Col nvarchar(max);
select @Col =
(
select distinct ','+quotename(Name)
from #T
for xml path(''),type
).value('substring(text()[1],2)','nvarchar(max)');
set @SQL = 'select '+@Col+'
from #T
pivot (max(Value) for Name in ('+@Col+')) as P';
exec (@SQL);
任何帮助将不胜感激。