1

我正在尝试编写一个 sql 查询,该查询将以我可以转换为 excel 电子表格的格式生成 xml。所以原来的sql表包含以下数据

id  Run     Name    Outcome
1   Run1    Test1   1
2   Run2    Test2   2

到目前为止,我设法生成的 sql 查询如下

select * from
(
    SELECT * from table1
  ) t
  for xml path('row'), root('sheetData')

这将产生以下 xml

  <sheetData>
  <row r="1">
    <Run>Run1</Run>
    <Name>Test1</Name>
    <Outcome>1</Outcome>
  </row>
   <row r="2">
    <Run>Run2</Run>
    <Name>Test2</Name>
    <Outcome>2</Outcome>
  </row>
</sheetData>

所以我需要得到的是下面的xml格式

  <?xml version="1.0" encoding="UTF-8"?>
<sheetData>
   <row r="1">
      <c r="A1" t="inlineStr">
         <is>
            <t>Run1</t>
         </is>
      </c>
      <c r="B1" t="inlineStr">
         <is>
            <t>Test1</t>
         </is>
      </c>
      <c r="C1" t="inlineStr">
         <is>
            <t>1</t>
         </is>
      </c>       
   </row>
   <row r="2">
      <c r="A2" t="inlineStr">
         <is>
            <t>Run2</t>
         </is>
      </c>
      <c r="B2" t="inlineStr">
         <is>
            <t>Test2</t>
         </is>
      </c>
      <c r="C2" t="inlineStr">
         <is>
            <t>2</t>
         </is>
      </c>       
   </row>
</sheetData>

现在我已经求助于对第一个 xml 格式进行转换以获得所需的输出,但是我希望构建一个 sql 查询,我可以使用它来直接生成它,而无需进行额外的转换。谢谢你的帮助。

4

1 回答 1

1

以下将做你想要的。

DECLARE @Data TABLE (
    [id] INT,
    [Run] NVARCHAR(20),
    [Name] NVARCHAR(20),
    [Outcome] INT
)

INSERT INTO
    @Data ( [id], [Run], [Name], [Outcome] )
VALUES
    ( 1, 'Run1', 'Test1', 1 ),
    ( 2, 'Run2', 'Test2', 2 )

DECLARE @Xml XML = (
    SELECT
        [Id] AS [@r],
        (SELECT
            'A'+CONVERT(nvarchar(20), [Id]) AS [@r],
            'inlineStr' AS [@t],
            (SELECT
                [Run] AS [t]
            FOR XML PATH('is'), TYPE)
        FOR XML PATH('c'), TYPE),

        (SELECT
            'B'+CONVERT(nvarchar(20), [Id]) AS [@r],
            'inlineStr' AS [@t],
            (SELECT
                [Name] AS [t]
            FOR XML PATH('is'), TYPE)
        FOR XML PATH('c'), TYPE),

        (SELECT
            'C'+CONVERT(nvarchar(20), [Id]) AS [@r],
            'inlineStr' AS [@t],
            (SELECT
                [Outcome] AS [t]
            FOR XML PATH('is'), TYPE)
        FOR XML PATH('c'), TYPE)

    FROM
        @Data
    FOR XML PATH('row'), ROOT('sheetData'), TYPE
)
SELECT
    '<?xml version="1.0" encoding="UTF-8"?>'
    +CONVERT(NVARCHAR(MAX), @Xml)
于 2014-06-12T14:55:25.317 回答