一、准备
for xml path它以xml形式展示查询的结果集。
声明一张表,表中内容如下。
二、基本语法
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>
三、更改节点名称
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>
四、更改列的名称
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>
五、自定义输出格式
select '{'+ltrim(str(ID))+'}'+'['+RealName+']' from Blog_UserInfo for xml path('')
查询结果
{1}[金某]{2}[李某]{3}[赵某]
六、场景应用
需求:查询出每个学生的所有爱好集
查询语句
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
运行结果