我需要使用“For XML explicit”和CDATA指令从SQL Server 2008 R2生成XML。输出应如下所示: -
<?xml version="1.0" encoding="utf-8" ?>
<JOB>
<AD>
<ID><![CDATA[ 451 ]]></ID>
<TITLE><![CDATA[ Receptionist ]]></TITLE>
</AD>
<AD>
<ID><![CDATA[ 1025 ]]></ID>
<TITLE><![CDATA[ Secretary ]]></TITLE>
</AD>
</JOB>
虽然,表的架构是,
Table Name : AD
Column1 : ID
Column2 : TITLE
但是,我无法实现这一目标并陷入某个地方。
非常感谢。
答案 0 :(得分:4)
declare @T table(ID int, TITLE varchar(50))
insert into @T values(451, 'Receptionist')
insert into @T values(1025, 'Secretary')
select 1 as Tag,
null as Parent,
ID as [AD!1!ID!CDATA],
TITLE as [AD!1!TITLE!CDATA]
from @T
order by [AD!1!ID!CDATA]
for xml explicit
结果:
<AD>
<ID><![CDATA[451]]></ID>
<TITLE><![CDATA[Receptionist]]></TITLE>
</AD>
<AD>
<ID><![CDATA[1025]]></ID>
<TITLE><![CDATA[Secretary]]></TITLE>
</AD>
修改强> 使用根节点:
declare @T table(ID int, TITLE varchar(50))
insert into @T values(451, 'Receptionist')
insert into @T values(1025, 'Secretary')
select 1 as Tag,
null as Parent,
null as [JOB!1],
null as [AD!2!ID!CDATA],
null as [AD!2!TITLE!CDATA]
union all
select 2 as Tag,
1 as Parent,
null,
ID,
TITLE
from @T
order by Tag, [AD!2!ID!CDATA]
for xml explicit
答案 1 :(得分:0)
关于根节点,更新版本的MSSQL允许更容易编写:
FOR XML EXPLICIT, ROOT('***YOURROOTTAGNAME***')