键值对XML(SQL Server 2005)

时间:2014-02-25 09:14:44

标签: sql-server tsql sql-server-2005 sqlxml

我目前正在使用这个:

SELECT Column1, Column2
FROM SomeTable 
FOR XML PATH(''), ROOT('KeyValuePairs')

产生这个:

<KeyValuePairs>
<Column1>ColumValue1</Column1>
<Column2>ColumValue1</Column2>
</KeyValuePairs>

是否有办法制作更具描述性的内容:

<KeyValuePairs>
<KeyValuePair><Key>Column1</Key><Value>ColumValue1</Value></KeyValuePair>
<KeyValuePair><Key>Column2</Key><Value>ColumValue2</Value></KeyValuePair>
</KeyValuePairs>

1 个答案:

答案 0 :(得分:2)

SELECT (
       SELECT 'Column1' AS [Key],
              T.Column1 AS Value
       FOR XML PATH('KeyValuePair'), TYPE
       ),
       (
       SELECT 'Column2' AS [Key],
              T.Column2 AS Value
       FOR XML PATH('KeyValuePair'), TYPE
       )
FROM SomeTable AS T
FOR XML PATH('KeyValuePairs')

替代:

SELECT  'Column1' AS [KeyValuePair/Key],
        T.Column1 AS [KeyValuePair/Value],
        NULL,
        'Column2' AS [KeyValuePair/Key],
        T.Column2 AS [KeyValuePair/Value]
FROM SomeTable AS T
FOR XML PATH('KeyValuePairs')