FOR XMI PATH,STUFF 实现字段拼接

来源:互联网 发布:eureka api java 编辑:程序博客网 时间:2024/05/17 23:02
create table testa (college nvarchar(20)  not null,dept nvarchar(20) not null,name nvarchar(20) not null)insert into testa(college,dept,name) values('信息工程学院','计算机','张三'),('信息工程学院','计算机','李四'),('信息工程学院','计算机','王五'),('信息工程学院','信管','赵毅'),('信息工程学院','信管','孙华'),('信息工程学院','计合','小明'),('信息工程学院','计合','学军'),('财税学院','会计','张茜'),('财税学院','会计','蒋业'),('财税学院','税务','黄婷婷'),('财税学院','税务','金星')select * from testa  

返回结果:

college dept name 信息工程学院 计算机 张三 信息工程学院 计算机 李四 信息工程学院 计算机 王五 信息工程学院 信管 赵毅 信息工程学院 信管 孙华 信息工程学院 计合 小明 信息工程学院 计合 学军 财税学院 会计 张茜 财税学院 会计 蒋业 财税学院 税务 黄婷婷 财税学院 税务 金星
select * from testa  for xml path返回结果<row>  <college>信息工程学院</college>  <dept>计算机</dept>  <name>张三</name></row><row>  <college>信息工程学院</college>  <dept>计算机</dept>  <name>李四</name></row><row>...select * from testa  for xml path ('haha')返回结果<haha>  <college>信息工程学院</college>  <dept>计算机</dept>  <name>张三</name></haha><haha>  <college>信息工程学院</college>  <dept>计算机</dept>  <name>李四</name></haha>
select '['+college+']','['+dept+']','['+name+']' from testa for xml path('') --返回结果:[信息工程学院][计算机][张三][信息工程学院][计算机][李四][信息工程学院][计算机][王五][信息工程学院][信管][赵毅]--根据系名分组,将姓名连接select dept,(select ',' + namefrom testa where dept=a.dept for xml path('')) as namefrom testa a group by dept

返回结果:

dept name 会计 ,张茜,蒋业 计合 ,小明,学军 计算机 ,张三,李四,王五 税务 ,黄婷婷,金星 信管 ,赵毅,孙华
此时为了把name列前面的‘,’去掉,可以用stuff函数stuff(param1, startIndex, length, param2)说明:将param1中自startIndex(SQL中都是从1开始,而非0)起,删除length个字符,然后用param2替换删掉的字符。select stuff('abcdefg',3,2,'111111') 结果:  ab111111efgselect dept ,stuff(name,1,1,'')from(select dept,(select ',' + namefrom testa where dept=a.dept for xml path('')) as namefrom testa a group by dept)a

返回结果:

dept name 会计 张茜,蒋业 计合 小明,学军 计算机 张三,李四,王五 税务 黄婷婷,金星 信管 赵毅,孙华
原创粉丝点击