I have in my column (id) values
4
5
10
我想选择不存在的最小nubmer。示例值1然后是2然后是3然后是6 .....
我正在尝试此代码
IF not EXISTS(SELECT min(id) from table1) select...
答案 0 :(得分:0)
您可以找到不存在Id + 1行的第一行。
试试这个。
SELECT TOP 1 t1.Id+1 as ID
FROM table t1
WHERE NOT EXISTS(SELECT * FROM table t2 WHERE t2.Id = t1.Id + 1)
ORDER BY t1.Id;
检查一下.. Online Demo HERE
答案 1 :(得分:0)
Create a numbers table,这很容易:
SELECT MIN(Numbers.n) As MinMissingId
FROM [Numbers]
WHERE NOT EXISTS
(
SELECT 1 FROM dbo.TableName t WHERE Numbers.n = t.ID
)
这是一个小脚本,用于创建从Aaron文章中复制的表格:
SELECT TOP (1000000) n = CONVERT(INT, ROW_NUMBER() OVER (ORDER BY s1.[object_id]))
INTO dbo.Numbers
FROM sys.all_objects AS s1 CROSS JOIN sys.all_objects AS s2
OPTION (MAXDOP 1);
CREATE UNIQUE CLUSTERED INDEX n ON dbo.Numbers(n)
-- WITH (DATA_COMPRESSION = PAGE)
;