Using the instructions from the 1st answer here, I'm trying to shred some XML in a SQL Server 2012 table that looks like this:
TableA
+------+--------+
| ID | ColXML |
+------+--------+
| 0001 | <xml1> |
| 0002 | <xml2> |
| ... | ... |
+------+--------+
xml1 looks like this:
<Attributes>
<Attribute name="address1">301 Main St</Attribute>
<Attribute name="city">Austin</Attribute>
</Attributes>
xml2 looks like this:
<Attributes>
<Attribute name="address1">501 State St</Attribute>
<Attribute name="address2">Suite 301</Attribute>
<Attribute name="state">Texas</Attribute>
</Attributes>
There are varying numbers of attributes in any given row.
I'm trying to flatten it out into a relational table that looks like this:
+------+--------------+-----------+--------+-------+
| ID | address1 | address2 | city | state |
+------+--------------+-----------+--------+-------+
| 0001 | 301 Main St | NULL | Austin | NULL |
| 0002 | 501 State St | Suite 301 | NULL | Texas |
+------+--------------+-----------+--------+-------+
Here's the code that I've tried that returns 0 rows in table #T:
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);
Any help would be greatly appreciated.