SQL 2005,2008中生成XML结果集
自己也是刚学会,权作备注,如有错误,敬请请教
第一步部分:为演示造数据
SQL代码
![](/Images/OutliningIndicators/ContractedBlock.gif)
Code
declare @person table(
ID int ,
Name nvarchar(50) null,
Sex bit default(0) null,
Age int default(0) null
)
insert into @person
select 1,'张三',0,26 union all
select 2,'李四',0,26 ;
declare @tech table(
personID int not null,
Tech nvarchar(50) null
)
insert into @tech
select 1,'.net' union all
select 1,'javascript' union all
select 1,'sql' union all
select 2,'.net' union all
select 2,'javascript' union all
select 2,'sql' union all
select 2,'python' union all
select 2,'ruby';
第二部分:实战生成XML结果集,关键字:for xml auto,for xml raw,for xml explicit
最简单的生成XML结果集;
select * from @person for xml auto
select * from @person for xml raw
select * from @person for xml raw,root('person')
以上结果自己测试查看
关键在最后一方法上,for xml explicit,使用此模式你需要精确指定你要生成XML的结构,全部需要手动指定,相对比上面的麻烦些,
但却是最灵活的,相对麻烦些,也不算多么滴难,关键就在理解那个TAG,和PARENT上,前者为表示节点,后者表示节点的父节点,
OK,天机已被我道破,下面看代码和结果集,有个直观的印象
SQL代码
![](/Images/OutliningIndicators/ContractedBlock.gif)
Code
select
1 as tag,
null as parent,
null as [Name!1!],
Name as [Name!1!Name],
Sex as [Name!1!Sex],
Age as [Name!1!Age]
from @person
for xml explicit,root('person')
结果:
![](/Images/OutliningIndicators/ContractedBlock.gif)
Code
<person>
<Name Name="张三" Sex="0" Age="26" />
<Name Name="李四" Sex="0" Age="26" />
</person>
似乎没什么,和前边的差不多的结果,至少也要有个子节点啥的,才能与上边的简单查询区分开吧,继续
SQL 代码:
![](/Images/OutliningIndicators/ContractedBlock.gif)
Code
with aaa as (
select
1 as tag,
null as parent,
id,
null as [Name!1!],
Name as [Name!1!Name],
Sex as [Name!1!Sex],
Age as [Name!1!Age],
null as [Tech!2!]
from @person
union all
select
2 as tag,
1 as parent,
personId,
null,
null,
null,
null,
Tech
from @tech
)
select
tag,
parent,
[Name!1!],
[Name!1!Name],
[Name!1!Sex],
[Name!1!Age],
[Tech!2!]
from aaa
order by id,tag
for xml explicit,root('person')
结果:
![](/Images/OutliningIndicators/ContractedBlock.gif)
Code
<person>
<Name Name="张三" Sex="0" Age="26">
<Tech>.net</Tech>
<Tech>javascript</Tech>
<Tech>sql</Tech>
</Name>
<Name Name="李四" Sex="0" Age="26">
<Tech>.net</Tech>
<Tech>javascript</Tech>
<Tech>sql</Tech>
<Tech>python</Tech>
<Tech>ruby</Tech>
</Name>
</person>