MS-SQL SERVER单列合并的四种常用方法
/* 原始数据 ID Name ----------- -------------------- 1 吕布 2 张飞 3 赵云 结果 ----------------- 吕布,张飞,赵云 */ declare @t table(ID int identity,[Name] varchar(6)) insert into @t select '吕布' union all select '张飞' union all select '赵云' --方法一 declare @sql varchar(1000);set @sql = '' select @sql=@sql+[Name]+',' from @t set @sql=left(@sql,len(@sql)-1) select @sql as 结果1 /* 结果1 ---------------- 吕布,张飞,赵云 */ --方法二 declare @sqltwo varchar(8000) select @sqltwo=coalesce(@sqltwo+',','')+[Name] from @t select @sqltwo as 结果2 /* 结果2 --------------- 吕布,张飞,赵云 */ ---方法三 declare @sqlthree varchar(8000) select @sqlthree=isnull(@sqlthree+',','')+[Name] from @t select @sqlthree as 结果3 /* 结果3 ---------------- 吕布,张飞,赵云 */ --方法四 select reverse(stuff(reverse(( select [Name]+',' from @t for xml path(''))),1,1,'')) as 结果4 /* 结果4 ----------------- 吕布,张飞,赵云 */