我有一个主键字段ID的表.我不想使用Identity,因为我需要为用户提供手动选择新对象的ID的可能性.所以我的想法是:
问题是如何查询和SQL Server表获取第一个免费ID号?
例1:
ID
--
1
2
10
Run Code Online (Sandbox Code Playgroud)
首个免费ID为3
例2:
ID
--
1
2
3
4
Run Code Online (Sandbox Code Playgroud)
首个免费ID为5
有没有办法做到这一点?我能想到的是获取最小值和最大值,为可能的值创建一个循环,然后与表数据进行比较,但它涉及到数据库的太多查询.谢谢!
您可以找到第一个免费ID作为没有"下一个"值的第一个ID:
select coalesce(min(t.id) + 1, 0)
from table t left outer join
table t2
on t.id = t2.id - 1
where t2.id is null;
Run Code Online (Sandbox Code Playgroud)
编辑:
如果要将"1"作为潜在缺失值处理:
select (case when min(minid) > 1 then 1 else coalesce(min(t.id) + 1, 0) end)
from table t left outer join
table t2
on t.id = t2.id - 1 cross join
(select min(id) as minid from table t) const
where t2.id is null;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1196 次 |
| 最近记录: |