Username: Password:

连续编号的流水号拼接成一个字串的存储过程-数据库专栏,SQL Server
来源:作者: 发布时间:2007-12-25 13:46:53


网友提问:
---------------------------------------
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

喜欢本文,那就收藏到:

    Del.icio.us Google书签 Digg Live Bookmark Technorati Furl Yahoo书签 Facebook 百度搜藏 新浪ViVi 365Key网摘 天极网摘 和讯网摘 博拉网 POCO网摘 添加到饭否 QQ书签 Digbuzz我挖网
相关评论  我也要评论
还没有关于此文章的相关评论!
  • 昵称: (为空则显示guest)
  • 评论分数: ★ ★ ★★★ ★★★★ ★★★★★
  • 评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
  • 导航
    赞助商
    文章类别
    订阅