日期:2014-05-17 浏览次数:20576 次
declare @tb table(id int identity(1,1) not null,name nvarchar(5)) insert into @tb values('中'),('国'),('人'),('民') declare @str varchar(50) set @str='' select @str=@str+'+'+ name from @tb select RIGHT(@str,LEN(@str)-1 ) -------------------------------------------------- 中+国+人+民 (1 行受影响)
------解决方案--------------------
----------------------------------------------------
/*如何将一列中所有的值一行显示
数据源
a
b
c
d
e
结果
a,b,c,d,e
*/
create table tb(col varchar(20))
insert tb values ('a')
insert tb values ('b')
insert tb values ('c')
insert tb values ('d')
insert tb values ('e')
go
--方法一
declare @sql varchar(1000)
set @sql = ''
select @sql = @sql + t.col + ',' from (select col from tb) as t
set @sql='select result = ''' + left(@sql , len(@sql) - 1) + ''''
exec(@sql)
/*
result
----------
a,b,c,d,e,
*/
--方法二
declare @output varchar(8000)
select @output = coalesce(@output + ',' , '') + col from tb
print @output
/*
a,b,c,d,e
*/
drop table tb
------解决方案--------------------
WITH #001 AS( SELECT 1 AS id,'中' AS id_name UNION ALL SELECT 2 AS id,'国' AS id_name UNION ALL SELECT 3 AS id,'人' AS id_name UNION ALL SELECT 4 AS id,'民' AS id_name ) SELECT [拼接] = STUFF(( SELECT '+' + [id_name] FROM #001 ORDER BY id FOR XML PATH('') ), 1, 1, '') --输出: 拼接 中+国+人+民 (1 行受影响)
------解决方案--------------------
WITH #001 AS( SELECT 1 AS id,'中' AS id_name UNION ALL SELECT 2 AS id,'国' AS id_name UNION ALL SELECT 3 AS id,'人' AS id_name UNION ALL SELECT 4 AS id,'民' AS id_name ) SELECT [拼接] = STUFF(( SELECT '+' + [id_name] FROM #001 ORDER BY id FOR XML PATH('') ), 1, 1, '') --结果: 拼接 中+国+人+民 (1 行受影响)