在sql server中的xml中为同一个标记添加属性

时间:2012-01-31 14:42:44

标签: sql-server xml

我在sql server中有一个名为'Words'的表,其中包含以下列:Id,Type,Word

我想写一个查询来生成像这样的

<Words>
  <Word Id="1" Type="8">some text1</Word>
  <Word Id="2" Type="4">some text2</Word>
  <Word Id="3" Type="5">some text3</Word>
</Words>

我该怎么做?

1 个答案:

答案 0 :(得分:3)

WITH Words(Id, Type, Word) AS
(
SELECT 1, 8, 'some text1' UNION ALL
SELECT 2, 4, 'some text2' UNION ALL
SELECT 3, 5, 'some text3' 
)
SELECT Id   AS [@Id],
       Type AS [@Type],
       Word AS [text()]
FROM Words
FOR XML PATH('Word'), ROOT('Words')