網友提問:
---------------------------------------
test1表
id start end
1 1 5
2 6 10
3 21 25
4 26 30
5 51 60
希望得到結果:
string: 1-10,21-30,51-60
---------------------------------------
用變量拼接字串的解法:
--建測試表:
create table test1 ( id int,start int,[end] int)
--添加測試數(shù)據:
insert test1 select 1,1,5
union select 2,6,10
union select 3,21,25
union select 4,26,30
union select 5,51,60
--建立拼接字串的函數(shù):
create procedure proa
as
begin
declare @s varchar(8000)
--給變量賦表中第一行的相應值, cast(min(start)-1 這里是為了配合后面的全表查詢中的第一行給正確地接上。注意,如果流水號是從0開始,'-'要相應用其他字符如“+”號替代,最后 select @s 時,再改回‘-’號,具體的語句是:select replace(@s,'+','-'):
select @s= + cast(min(start) as varchar(10)) + '-'
+ cast(min(start)-1 as varchar(10))
from test1
--順序查詢并拼接字串:
select @s= left(@s,len(@s)-charindex('-',reverse(@s))+1)
+ case when cast(right(@s,charindex('-',reverse(@s))-1) as int)+1
=start
then cast([end] as varchar(20))
else right(@s,charindex('-',reverse(@s))-1) + ','
+ cast(start as varchar(10)) + '-'
+ cast([end] as varchar(10))
end
from test1
order by start
--返回結果:
select @s
end
--刪除測試表:
drop table test1
新聞熱點
疑難解答