如何在整数序列中找到第一个中断?

时间:2013-02-26 15:12:47

标签: sql tsql sql-server-2005 integer

想象一下,您有以下表格:

create table #myvalues(mykey int primary key)

您还有以下值:

insert into #myvalues(mykey) values(1)
insert into #myvalues(mykey) values(2)
insert into #myvalues(mykey) values(4)
insert into #myvalues(mykey) values(5)
insert into #myvalues(mykey) values(6)
insert into #myvalues(mykey) values(8)
insert into #myvalues(mykey) values(10)
insert into #myvalues(mykey) values(11)
insert into #myvalues(mykey) values(12)
insert into #myvalues(mykey) values(15)
insert into #myvalues(mykey) values(17)
insert into #myvalues(mykey) values(20)

您还有一个当前值:

declare @currentvalue int

select @currentvalue = 5

我想在@currentvalue之后找到此序列中的第一个中断。在这种情况下,答案是7.

我可以使用表变量并使用while循环旋转记录,但必须有更好的方法。

有什么建议吗?

3 个答案:

答案 0 :(得分:4)

WITH list
AS
(
    SELECT  myKey,
            ROW_NUMBER() OVER (ORDER BY myKey ASC) rn
    FROM    #myvalues
)
SELECT  TOP 1 rn
FROM    list
WHERE   myKey <> rn

这是占用starting value

的查询
DECLARE @currentValue INT 
SET @currentValue = 5

;WITH list
AS
(
    SELECT  myKey,
            ROW_NUMBER() OVER (ORDER BY myKey ASC) + (@currentValue - 1) rn
    FROM    myvalues
    WHERE   myKey >= @currentValue 
)
SELECT  TOP 1 rn 
FROM    list
WHERE   myKey <> rn

答案 1 :(得分:2)

您可以自己加入表格:

select top 1 t.mykey + 1
from myvalues t
left join myvalues x on x.mykey = t.mykey + 1
where t.mykey > @currentvalue and x.mykey is null
order by t.mykey

演示:http://www.sqlfiddle.com/#!2/c6dd2/7

答案 2 :(得分:2)

select top 1 myKey+1 from #myvalues
where 
    (myKey+1) not in (select mykey from #myvalues)
    and mykey >= @currentValue