2014-04-03 34 views
0

有沒有什麼辦法讓從開放的XML查詢XML輸出看起來像這樣SQL Open XML格式 - 價值主要= 「Col1中」

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

例如

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

回答

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> 
+0

很好,謝謝! – Hoody