SQL FOR XML PATH:不保留在节点中的属性

时间:2016-11-16 15:20:04

标签: sql sql-server xml tsql xpath

我有:

(SELECT TOP 1 '01' AS '@language', 'a description' as 'data()' FROM @tmpData AS  FOR XML PATH('description'),ROOT('course'),TYPE),  
(SELECT TOP 1 '2016-CRS' AS '@code' FROM @tmpData as t FOR XML PATH('course'),TYPE),

这表明:

<course>
        <description language="01">a description</description>
</course>
<course code="2016-CRS" />

但我真正需要的是:

<course code="2016-CRS">
        <description language="01">a description</description>
</course>

我知道这很简单,但我无法实现。感谢您的任何见解!

1 个答案:

答案 0 :(得分:0)

您的示例并不完全清楚,因为您使用数据源FROM @tmpData而根本不使用它,但这会返回您似乎需要的结果:

SELECT '2016-CRS' AS [@code] 
      ,'01' AS [description/@language]
      ,'a description' as [description]
FOR XML PATH('course')

结果

<course code="2016-CRS">
  <description language="01">a description</description>
</course>