日期:2014-05-18  浏览次数:20442 次

sql里怎样将一个表里查询出的多条记录第一个字段组成一个字符串
如题:
表A里只有一个字段,且里面的内容无规律:
A
a01  
-------------
aa  
34  
b1  

现定义一个字符串str

用循环怎样得到str="aa,34,b1"?

------解决方案--------------------
SQL code
declare @str varchar(20)
set @str=''
select @str=@str+','+LTRIM(a01) from A
select RIGHT(@str,LEN(@str)-1) as new

------解决方案--------------------
SQL code
declare @A table (a01 varchar(32))
insert @a select 'aa' union all select  '34' union all select 'b1'

declare @str varchar(20)
set @str=''
select @str=@str+','+LTRIM(a01) from @A
select RIGHT(@str,LEN(@str)-1) as new
/*
new
aa,34,b1
*/