I’m trying to transform a table to an XML struture and I want one of the columns in my table to represent a parent node and the other column to represent a child node.
I have got part of the way but I don’t have the complete solution. I need the TABLE_NAME column to transform to a xml parent node and the COLUMN_NAME column to transform as child nodes. If I execute the following I get the nesting but I also get multiple parent nodes.
select
TABLE_NAME AS 'tn',
COLUMN_NAME AS 'tn/cn'
from (
select 'TABLE_A' AS TABLE_NAME, 'COLUMN_1' AS COLUMN_NAME
UNION ALL
select 'TABLE_A' AS TABLE_NAME, 'COLUMN_2' AS COLUMN_NAME
UNION ALL
select 'TABLE_B' AS TABLE_NAME, 'COLUMN_1' AS COLUMN_NAME
UNION ALL
select 'TABLE_B' AS TABLE_NAME, 'COLUMN_2' AS COLUMN_NAME
) x
for xml path(''), ROOT('datatable')
OUPUT>>>
<datatable>
<tn>TABLE_A<cn>COLUMN_1</cn></tn>
<tn>TABLE_A<cn>COLUMN_2</cn></tn>
<tn>TABLE_B<cn>COLUMN_1</cn></tn>
<tn>TABLE_B<cn>COLUMN_2</cn></tn>
</datatable>
DESIRED OUTPUT >>>
<datatable>
<TABLE_A>
<cn>COLUMN_1</cn>
<cn>COLUMN_2</cn>
</TABLE_A>
<TABLE_B>
<cn>COLUMN_1</cn>
<cn>COLUMN_2</cn>
</TABLE_B>
</datatable>
Is this possible or am I dreaming? and is it possible without XML EXPLICIT or is this the kind of thing EXPLICIT is there for?
The other possiblity I’ve been trying is to stuff the xml and then apply an xquery, but no joy with that yet.
Thanks,
Gary
As others have mentioned,
FOR XMLdoesn’t allow you to dynamically name nodes. The node names have to be constants by the time the query itself is compiled. You can work around this with dynamic sql but then you end up with code that gets harder and harder to read.An alternative would be to manually generate the talbe name nodes and CAST into XML:
Setup:
Execute:
Produces: