日期:2014-05-17 浏览次数:20520 次
--查找连续编号区间
create table test(field varchar(03))
insert into test values('001')
insert into test values('002')
insert into test values('003')
insert into test values('005')
insert into test values('006')
insert into test values('008')
insert into test values('010')
insert into test values('011')
insert into test values('015')
insert into test values('016')
insert into test values('017')
go
;with cte_test
as
(
select field, field as new_field
from test as T
where not exists(select 1 from test where convert(int,field) = convert(int,T.field)-1)
union all
select A.field,B.field
from cte_test as A, test as B
where convert(int,A.new_field)+1= convert(int,B.field)
)
select field as [start],max(new_field) as [end]
from cte_test
group by field
order by [start]
/*
001 003
005 006
008 008
010 011
015 017
*/
GO
drop table test