合并多行到1行
[Table1]
ID,Name
1,aaa
2,bbb
3,ccc
4,ddd
5,eee
6,fff
7,ggg
select Name from Table1 where ID in(2,3,4)
取出行数据
bbb
ccc
ddd
我想要bbb,ccc,ddd这样的格式,即把查询到的结果合并到1行用逗号分隔,请问如何处理?
------解决方案--------------------declare @name varchar(2000)
select @name = isnull(@name + ',','') + Name from Table1 where ID in(2,3,4)
select @name as name
------解决方案--------------------declare @str varchar(1000)=''
select @str=@str+name+',' Table1 where ID in(2,3,4)
select substring(@str,1,len(@str)-1)
------解决方案--------------------
declare @s varchar(8000)
select @s=isnull(@s,'')+rtrim(Name)+',' from Table1 where ID in(2,3,4)
select @s as result
------解决方案--------------------declare @nname varchar(2000)
set @nname=''
select @nname=@nname+','+[Name] from Table1 where ID in(2,3,4)
select @nname
------解决方案--------------------select stuff((select ','+Name from Table1 where ID in(2,3,4) for xml path('')),1,1,'')