SQL Open XML格式 - 值键=“Col1”

时间:2014-04-03 12:59:08

标签: sql-server xml tsql

有没有办法让OPEN XML查询的XML输出看起来像这样

<TableName>
<Value Key="Col1">Col1 Value</Value>
<Value Key="Col2">Col2 Value</Value>
<Value Key="Col3">Col3 Value</Value>
etc.......

E.g。

<FooBar>
<Value Key="Name">Mr Woo</Value>
<Value Key="Age">22</Value>
<Value Key="Location">The Moon</Value>
</FooBar>

1 个答案:

答案 0 :(得分:3)

SQL Fiddle

MS SQL Server 2012架构设置

create table T
(
  Name varchar(10),
  Age int,
  Location varchar(10)
);

insert into T values('Mr Woo', 22, 'The Moon');

查询1

select 'Name' as [Value/@Key],
       Name as [Value],
       null,
       'Age' as [Value/@Key],
       Age as [Value],
       null,
       'Location' as [Value/@Key],
       Location as [Value]
from T
for xml path('FooBar')

<强> Results

<FooBar>
  <Value Key="Name">Mr Woo</Value>
  <Value Key="Age">22</Value>
  <Value Key="Location">The Moon</Value>
</FooBar>