我有一张这样的表:
ID Name Column1 Column2 Column3
1 ABC 202.2 1500 34000
2 IJK 104 10000 27000
我想生成这样的XML:
<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>
我从this forum post得到了一些线索并使用了这段代码:
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>
')
我尝试了以下修改版本:
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>')
但我收到错误:
XQuery [query()]: Invalid source character 0x7b found in an identifier
near 'return'.
答案 0 :(得分:1)
为什么你想要得到幻想。
Select * from #tmp as record
FOR XML AUTO, root('doc')