
网友提问: --------------------------------------- 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)
--添加测试数据: 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
--建立拼接字串的函数: 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
|