使用for xml生成带键/值结构的xml

时间:2012-02-09 19:58:29

标签: sql xml sql-server-2008 tsql

我正在尝试生成此

<Mail>
  <Field key="SenderName" value="someone" />
  <Field key="RecipientName" value="someone else" />
<Mail/>
<Mail>
  <Field key="SenderName" value="another someone" />
  <Field key="RecipientName" value="another someone else" />
<Mail/>

继承测试数据

declare @tab table (SenderName varchar(255), RecipientName varchar(255))
insert @tab
select 'someone' , 'someone else' union 
select 'another someone' , 'another someone else' 

我已经为xml路径尝试了各种各样的东西,但是我不知道如何告诉声明我想在收件人名称后面想要一个同名的新元素。

感谢,

1 个答案:

答案 0 :(得分:2)

declare @tab table (SenderName varchar(255), RecipientName varchar(255))
insert @tab
select 'someone' , 'someone else' union 
select 'another someone' , 'another someone else' 

select (select 'SenderName' as "@key",
                SenderName  as "@value"
        for xml path('Field'), type),
       (select 'RecipientName' as "@key",
                RecipientName  as "@value"
        for xml path('Field'), type) 
from @tab
for xml path('Mail')