2

假设您有以下表格:

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 循环遍历记录,但必须有更好的方法。

有什么建议么?

4

3 回答 3

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
于 2013-02-26T15:15:45.590 回答
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

于 2013-02-26T15:18:42.980 回答
2
select top 1 myKey+1 from #myvalues
where 
    (myKey+1) not in (select mykey from #myvalues)
    and mykey >= @currentValue
于 2013-02-26T15:22:00.040 回答