【问题标题】:Microsoft SQL Server 2014 change format of generated xmlMicrosoft SQL Server 2014 更改生成的 xml 的格式
【发布时间】:2017-01-31 23:29:16
【问题描述】:

我在 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>

我怎样才能做到这一点?我尝试将“auto”更改为“raw”或“path”,但没有成功。

你好,拉法乌

【问题讨论】:

    标签: sql sql-server xml tsql


    【解决方案1】:
    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>
    

    【讨论】:

    • 嗨,恭喜获得 SQL-Server Golden Badge :-) 我知道,没有气球 :-)
    • @Shnugo 谢谢。不用担心,我为这种场合准备了一个供应派对的帽子和噪音制造器......当你想到它时它有点难过。
    • @Rafalsonn 很高兴它有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多