FOR XML PATH具有重复的列名称

时间:2016-12-23 21:09:21

标签: sql-server xml

我正在尝试使用FOR XML PATH从MS SQL Server 2012获取所需的输出。

我的查询基本上是这样的:

select field1 as fields, field2 as fields, field3 as fields 
from mytable 
for xml path

产生这个xml :(对于fieldN列中的值0,3,7)

<row>
    <fields>037</fields>
</row>

我想要的输出是:

<row>
    <fields>0</fields>
    <fields>3</fields>
    <fields>7</fields>
</row>

这可能吗?

1 个答案:

答案 0 :(得分:4)

Declare @YourTable table (Field1 int,Field2 int,Field3 int)
Insert Into @YourTable values (0,3,7),(8,9,10)

Select [fields] = Field1
      ,''
      ,[fields] = Field2
      ,''
      ,[fields] = Field3
 From  @YourTable
 For   XML Path('row')

返回

<row>
  <fields>0</fields>
  <fields>3</fields>
  <fields>7</fields>
</row>
<row>
  <fields>8</fields>
  <fields>9</fields>
  <fields>10</fields>
</row>