SQL 查詢跳號

摘要:SQL 查詢跳號

要做的事情是:在流水號裡找出跳號;比如說,1.2.3.5.6.8.9...要列出4.7

寫了寫才想到,可能不是只跳一號,1.2.5,要列出 3.4,跳幾號未知→迴圈→囧,也不是做不到,就是囉嗦了點。

declare @t table (idx int)

insert @t values(1)
insert @t values(2)
insert @t values(3)
insert @t values(5)
insert @t values(6)
insert @t values(8)
insert @t values(15)

select *
, (select isnull(max(idx),0) from @t t2 where t2.idx<t1.idx) pre
, (select isnull(max(idx),0) from @t t2 where t2.idx<t1.idx)-idx flag -- [-1 = 沒跳號]
into #test
from @t t1

select * from #test where flag<>-1

;with rep as(
select idx+flag+1 miss, flag+1 flag from #test where flag<>-1
union all
select miss+1 miss, flag+1 flag from rep where flag<>-1
)
select * from rep

drop table #test