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

把一列拼接成字符串
select id from A
结果为
1
2
3
4
我现在想结果为1,2,3,4

在sqlserver2005中,这个该怎么写呢?请教,谢谢啦!

------解决方案--------------------
SQL code

DECLARE @T TABLE
(
  tid INT
)
INSERT INTO @T
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 

DECLARE @sql VARCHAR(50) 
SET @sql=''
SELECT @sql=@sql+','+CAST(tid AS VARCHAR(4)) FROM @T
PRINT right(@sql,LEN(@sql)-1)
/*

(所影响的行数为 4 行)

1,2,3,4

*/

------解决方案--------------------
SQL code
create table #Test(id int)
insert into #Test
select 1 union all
select 2 union all
select 3 union all
select 4

select * from #Test

declare @Str varchar(100)
set @Str=''
select @Str=@Str+','+cast(id as varchar(100)) from #Test
select stuff(@Str,1,1,'')
//1,2,3,4