SQL Server 查询结果多行数据拼接

来源:互联网 发布:淘宝和拍拍网的区别 编辑:程序博客网 时间:2024/05/18 03:05

查询语句:

select fd_name from sys_org_element where fd_org_type = 8 and fd_id > '1525a3e6a6744de7ea346d74567b9a47'

显示结果:

fd_name
许镁琪
吴成环
许晓云

将多行数据拼接显示:

select STUFF((select ',' + fd_name from sys_org_element where fd_org_type = 8 and fd_id > '1525a3e6a6744de7ea346d74567b9a47'for xml path('')),1,1,'')

显示结果:

许镁琪,吴成环,许晓云


/******************************************************************/


for xml path :将查询结果集以xml形式展现;

从下面几个例子可以大概了解其用法:

select fd_name,fd_nofrom sys_org_element where fd_org_type = 8 and fd_id > '1525a3e6a6744de7ea346d74567b9a47'for xml path('')

查询结果:

<fd_name>许镁琪</fd_name><fd_no>1601003409</fd_no><fd_name>吴成环</fd_name><fd_no>1601003410</fd_no><fd_name>许晓云</fd_name><fd_no>1601003411</fd_no>

语句:

select '['+fd_name+']',fd_no as nofrom sys_org_element where fd_org_type = 8 and fd_id > '1525a3e6a6744de7ea346d74567b9a47'for xml path('')

查询结果:

[许镁琪]<no>1601003409</no>[吴成环]<no>1601003410</no>[许晓云]<no>1601003411</no>

stuff函数:

stuff(param1, start, length, param2)

将param1中从start位置起(从1开始),长度为length的字串替换为param2;

实例:

select stuff('abcdef',2,3,'xxoo')

查询结果:

axxooef





0 0
原创粉丝点击