数据库学习:for xml path

一、开发环境

数据库:SQLServer2012

二、语法简介

for xml path它以xml形式展示查询的结果集

三、语法介绍

现在数据库中有一张表

image

1.基本语法

select * from Blog_UserInfo for xml path

运行结果:

<row>
  <ID>1</ID>
  <Introduce>大家好,我叫金某</Introduce>
  <RealName>金某</RealName>
</row>
<row>
  <ID>2</ID>
  <Introduce>大家好,我叫李某</Introduce>
  <RealName>李某</RealName>
</row>
<row>
  <ID>3</ID>
  <Introduce>大家好,我叫赵某</Introduce>
  <RealName>赵某</RealName>
</row>

2.更改根节点名称

语法:

select * from Blog_UserInfo for xml path('UserInfo')

运行结果:

<UserInfo>
  <ID>1</ID>
  <Introduce>大家好,我叫金某</Introduce>
  <RealName>金某</RealName>
</UserInfo>
<UserInfo>
  <ID>2</ID>
  <Introduce>大家好,我叫李某</Introduce>
  <RealName>李某</RealName>
</UserInfo>
<UserInfo>
  <ID>3</ID>
  <Introduce>大家好,我叫赵某</Introduce>
  <RealName>赵某</RealName>
</UserInfo>

3.更改列的名字

语法:

select ID as 'myID',Introduce as 'myIntrodece',RealName as 'myRealName' from Blog_UserInfo for xml path('UserInfo')

运行结果:

<UserInfo>
  <myID>1</myID>
  <myIntrodece>大家好,我叫金某</myIntrodece>
  <myRealName>金某</myRealName>
</UserInfo>
<UserInfo>
  <myID>2</myID>
  <myIntrodece>大家好,我叫李某</myIntrodece>
  <myRealName>李某</myRealName>
</UserInfo>
<UserInfo>
  <myID>3</myID>
  <myIntrodece>大家好,我叫赵某</myIntrodece>
  <myRealName>赵某</myRealName>
</UserInfo>

4.自定义输出格式

语法:

select '{'+ltrim(str(ID))+'}'+'['+RealName+']' from Blog_UserInfo for xml path('')

运行结果:

{1}[金某]{2}[李某]{3}[赵某]

四、场景应用

现有一张如下表

image

需求:查询出每个学生的所有爱好集

代码:

select c.Name,left(c.StuList,len(StuList)-1)as hobby from
(
select Name,
(select Hobby +',' from Blog_UserHobby a 
where a.Name = b.Name
for xml path(''))as StuList
from Blog_UserHobby b
group by b.Name
)c

运行结果:

image

五、参考文章

http://www.cnblogs.com/qixuejia/p/4242078.html

posted @ 2016-03-12 18:38  Kimisme  阅读(845)  评论(0编辑  收藏  举报