gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:59:28 24 4
gpt4 key购买 nike

我遇到类似于以下问题的情况:

Insert Data Into SQL Table

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

最佳答案

试试这个:

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

输出:

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

(1 row(s) affected)

编辑
这将给出相同的结果:

;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

关于SQL Server 2005 - 查找范围内的最小未使用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2701286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com