0

我有一张这样的桌子:

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>

我从这个论坛帖子中得到了一些线索并使用了这个代码:

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'.
4

1 回答 1

1

为什么你想变得花哨。

Select  * from #tmp as record
FOR XML AUTO,  root('doc')
于 2011-12-23T05:25:43.580 回答