SQL Server 2005 - 查找范围内的最小未使用值

Geo*_*Ego 4 sql sql-server sql-server-2005

我有类似以下问题的情况:

将数据插入SQL表

我的场景不同的地方是我有一个非自动递增的主键字段,其范围可以在1000和1999之间.到目前为止我们只有大约一百个值,但是已经取得了最大值(1999) ,编号顺序也有差距.因此,我需要找到一个介于1000-1999之间但未采用的值.例如,如果我当前的值是,例如,1000,1001,1003和1999,我希望查询返回1002.

KM.*_*KM. 5

试试这个:

declare @YourTable table (PK int)
insert @YourTable VALUES (1)
insert @YourTable VALUES (2)
insert @YourTable VALUES (4)
insert @YourTable VALUES (7)
insert @YourTable VALUES (8)


SELECT
    MIN(y.PK)+1
    FROM @YourTable                 y
        LEFT OUTER JOIN @YourTable y2 ON y.PK+1=y2.PK 
    WHERE y.PK>=1 AND y.PK<10 AND y2.PK IS NULL
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

-----------
3

(1 row(s) affected)
Run Code Online (Sandbox Code Playgroud)

编辑
这将得到相同的结果:

;with N AS 
(SELECT TOP 1000 row_number() over(order by t1.object_id) as Number
     FROM sys.objects t1 
     CROSS JOIN sys.objects t2
)
SELECT
    MIN(Number) AS PK
    FROM N
        LEFT OUTER JOIN @YourTable y on n.Number=y.PK
    WHERE y.PK IS Null
Run Code Online (Sandbox Code Playgroud)