我需要从SQL Server返回XML格式的列别名。由于XML列名称中不能包含空格,因此我想在“columnName”属性中返回此别名。通常,XML需要如下所示:
<customers>
<customer name="Shmo, Joe">
<over50 columnName="Number of Orders Over 50 Pounds" value="10">
<cancelled columnName="Orders Cancelled" value="2">
</customer>
</customers>
该表如下所示:
|Name |over50|cancelled
---------------------------
|Shmo, Joe| 10 | 2
如果可能,我真的想使用XML提取的“FOR XML”方法。提前感谢任何见解。
答案 0 :(得分:2)
这应该这样做。
SELECT Name AS [@name],
'Number of Orders Over 50 Pounds' AS [over50/@columnName],
over50 AS [over50/@value],
'Orders Cancelled' AS [cancelled/@columnName],
cancelled AS [cancelled/@value]
FROM YourTable
FOR XML PATH('customer'), ROOT('customers')