Microsoft SQL Server 2014更改生成的xml格式

时间:2017-01-31 23:29:17

标签: sql sql-server xml tsql

我在SQL Server中使用FOR XML功能,但我想更改生成的xml的格式。

这是我的疑问:

SELECT * 
FROM dbo.myTable AS row 
FOR XML RAW, ELEMENTS, ROOT('rows')

结果是:

<rows>
    <row>
       <name>A Time to Kill</name>
       <author>John Grisham</author>
       <price>12.99</price>
    </row>
    <row>
       <name>Blood and Smoke</name>
       <author>Stephen King</author>
       <price>10</price>
    </row>
</rows>

但我想要的结果是:

<rows> 
    <row id="1"> 
        <cell>A Time to Kill</cell> 
        <cell>John Grisham</cell> 
        <cell>12.99</cell> 
    </row>
    <row id="2"> 
        <cell>Blood and Smoke</cell> 
        <cell>Stephen King</cell> 
        <cell>10</cell> 
    </row>
</rows>

我怎样才能做到这一点?我试图改变“原始”或“路径”的“自动”,但它不起作用。

问候,Rafał

1 个答案:

答案 0 :(得分:4)

Declare @YourTable table (id int,name varchar(50),author varchar(50),price money)
Insert Into @YourTable values 
 (1,'A Time to Kill','John Grisham',12.99)
,(2,'Blood and Smoke','Stephen King',10)

Select [@id]  = id
      ,[cell] = name
      ,null
      ,[cell] = author
      ,null
      ,[cell] = price
 From  @YourTable
 For   XML Path('row'),root('rows')

返回

<rows>
  <row id="1">
    <cell>A Time to Kill</cell>
    <cell>John Grisham</cell>
    <cell>12.9900</cell>
  </row>
  <row id="2">
    <cell>Blood and Smoke</cell>
    <cell>Stephen King</cell>
    <cell>10.0000</cell>
  </row>
</rows>