日期:2014-05-17  浏览次数:20576 次

请教sql字符串相加
请教sql字符串相加



ID,Name
1 中
2 国
3 人
4 民

求一条SQL语句

查询出的结果是:中+国+人+民

越简单语句越好,千万不要写的太复杂。就一条语句,让SQL输出成上面的结果。
谢谢!

------解决方案--------------------
SQL code
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
------解决方案--------------------
SQL code

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 行受影响)

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

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 行受影响)