SQL Server:FOR XML特定输出

时间:2015-11-11 22:39:23

标签: sql sql-server xml sql-server-2008 tsql

我一直在尝试(尚未成功)生成以下XML输出

<table>
    <row>
        <column name="column_name">[value]</column>
        <column name="column_name">[value]</column>
    </row>
    <row>
        <column name="column_name">[value]</column>
        <column name="column_name">[value]</column>
    </row>
</table>

任何人都可以建议一条允许我实现此输出的路线吗?

提前感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

不知道这是否仍有意义,但代码是:

(诀窍是&#34;空节点&#34;两列声明之间......)

DECLARE @tbl TABLE(col1 INT, col2 VARCHAR(100));
INSERT INTO @tbl VALUES(1,'test1'),(2,'test2');

SELECT 'col1' AS [column/@name]
      ,col1 AS [column]

      ,'' --this is needed to allow the same name twice...

      ,'col2' AS [column/@name]
      ,col2 AS [column]
FROM @tbl
FOR XML PATH('row'),ROOT('table');

/*
<table>
  <row>
    <column name="col1">1</column>
    <column name="col2">test1</column>
  </row>
  <row>
    <column name="col1">2</column>
    <column name="col2">test2</column>
  </row>
</table>
*/