Search code examples
t-sqlfor-xml-path

Generate XML from Table


I have a table like this:

ID    Name    Column1    Column2    Column3

1     ABC     202.2      1500       34000
2     IJK     104        10000      27000

I want to generate XML like this:

<doc>
    <record ID="1" Name="ABC" Column1="202.2" Column2="15000" Column3="34000" />
    <record ID="2" Name="IJK" Column1="104" Column2="10000" Column3="27000" />
</doc>

I have got some clue from this forum post and used this code:

CREATE TABLE #tmp (column1 VARCHAR(20), column2 VARCHAR(20), column3 VARCHAR(20))

INSERT INTO #tmp VALUES ( 'data1', 'data2', 'data3' )
INSERT INTO #tmp VALUES ( 'data11', 'data21', 'data31' )

-- FOR XML PATH with ELEMENTS will automatically unpivot the data for you
-- Then reshape your XML using nested FLWOR loops
SELECT
    (
    SELECT *
    FROM #tmp t
    FOR XML PATH, ELEMENTS, TYPE
    ).query('
for $e in row
 return 
 <row>{
  for $f in $e/*
   return <field name="{local-name($f)}">{data($f)}</field>
     }
 </row>
')

I tried the following modified version:

SELECT (SELECT * FROM cte_temp t FOR XML PATH, ELEMENTS, TYPE)
.query('for $e in row return 
 <doc> 
 {
        for $f in $e return <record {local-name($f)}="{data($f)}" />
 }
</doc>')

But I'm getting error:

XQuery [query()]: Invalid source character 0x7b found in an identifier 
                  near 'return'.

Solution

  • Why you trying to get fancy.

    Select  * from #tmp as record
    FOR XML AUTO,  root('doc')