将sql表转换为xml名称值对

时间:2014-03-07 09:57:29

标签: sql sql-server sql-server-2008

您好我需要转换一个sql表数据,其字段名为 actionname,actiondesc 我需要将其转换为以下格式

   <Details>
   <Field name="actiondesc" value="val1"/>
    <Field name="actionname" value="val2"/>
     </Details>

提前致谢 阿伦

1 个答案:

答案 0 :(得分:2)

SQL Fiddle

MS SQL Server 2008架构设置

create table dbo.YourTable
(
  actiondesc int,
  actionname int
);

insert into dbo.YourTable values(1,2);
insert into dbo.YourTable values(3,4);

查询1

select 'actiondesc' as [Field/@name],
       T.actiondesc as [Field/@value],
       '',
       'actionname' as [Field/@name],
       T.actionname as [Field/@value]
from dbo.YourTable as T
for xml path('Details')

<强> Results

<Details>
  <Field name="actiondesc" value="1" />
  <Field name="actionname" value="2" />
</Details>
<Details>
  <Field name="actiondesc" value="3" />
  <Field name="actionname" value="4" />
</Details>