有一个表如下:
id name fieldsx fieldsn ...
===================================================================
1 王明 xxx bbbbb
2 张三 xxx bbbbb
3 李四 yyy aaaaa
4 赵五 sfa asfsafasf
.... ...... ...... ......
.... ...... ...... ......--------------------------------------------------------------------在不通过游标遍历的情况下,如何只通过一个查询立即取得定长的name的聚合序列(用逗号分开).得到的结果需要是这个:
王明,张三,李四,赵五.....
即每行的name的累加字串.
id name fieldsx fieldsn ...
===================================================================
1 王明 xxx bbbbb
2 张三 xxx bbbbb
3 李四 yyy aaaaa
4 赵五 sfa asfsafasf
.... ...... ...... ......
.... ...... ...... ......--------------------------------------------------------------------在不通过游标遍历的情况下,如何只通过一个查询立即取得定长的name的聚合序列(用逗号分开).得到的结果需要是这个:
王明,张三,李四,赵五.....
即每行的name的累加字串.
set @strName = ''
select @strName = @strName + name + ',' from TableName
print left(@strName,len(@strName) - 1)
set @str = ''
select @str = @str + ',' + name from table
set @str = stuff(@str,1,1,'')
create table test(name varchar(10))
insert test select '王明'
union all select '张三'
union all select '李四'
union all select '赵五'declare @s varchar(200)
set @s=''
select @s=@s+','+name from test
select stuff(@s,1,1,'')
print @s