2015-05-26 71 views
0

選擇到XML我有表包含三列:從表中的SQL Server具有鮮明的ID

[ID],[Name],[Value] 

我選擇了XML結果:

DECLARE @xml XML  
SET @xml = (
     SELECT 
       ID 
       ,[Name] 
       ,[Value] 
      FROM [CustomerDetails] 
      WHERE ID = 1 
     FOR XML PATH(''), ROOT('Customer') 
     )  
    SELECT @xml 

我選擇返回XML有多個ID屬性:

<Customer> 
    <ID>1</ID> 
    <Name>FirstName</Name> 
    <Value>firstName</Value> 
    <ID>1</ID> 
    <Name>LastName</Name> 
    <Value>lastName</Value> 
    <ID>1</ID> 
    <Name>Age</Name> 
    <Value>20</Value> 
    <ID>1</ID> 
    <Name>City</Name> 
    <Value>London</Value> 
</Customer> 

我下一步需要XML:

<Customer> 
     <ID>1</ID> 
     <Name>FirstName</Name> 
     <Value>firstName</Value> 
     <Name>LastName</Name> 
     <Value>lastName</Value> 
     <Name>Age</Name> 
     <Value>20</Value> 
     <Name>City</Name> 
     <Value>London</Value> 
    </Customer> 

如何返回這種XML?列

回答

1

我已經縮短名稱:

declare @id int = 1 

select id, n, v from 
(select @id id, null n, null v, 1 as rn from t 
union 
select null, n, v, 2 as rn from t 
where id = @id 
) t order by rn 
for xml path(''), root('customer') 

輸出:

<customer><id>1</id><n>n1</n><v>v1</v><n>n2</n><v>v2</v><n>n3</n><v>v3</v></customer> 

小提琴http://sqlfiddle.com/#!3/70ea0/4

+0

謝謝,非常 – zrabzdn

+0

歡迎您。 –