1

可能重复:
在 SQL Server 中查找最小的未使用数字

我在 Sql server 中有这张表

ID |  LetterID | LetterName

ID => int 和身份

LetterID => int and unique and NotNull

字母名称 => 字符串

LetterID从我的 C# 应用程序和用户设置的编号中填充它。例如 1,2,3,4,5,...,100,..(每行增加一个单位)现在我LetterID100但有时用户删除一行例如从表中删除行在哪里LetterID50现在插入新行(在应用程序中)我建议他LetterID选择50,如何从表中获取丢失的数字?

4

4 回答 4

1
var output =  Enumerable.Range(1, list.Max(item => item.LetterID))
          .Except(list.Select(item => item.LetterID))
于 2012-08-22T11:40:02.683 回答
0
select t1.ID, t1.LetterID-1 
from yourtable t1
    left join yourtable t2 
on t1.LetterID = t2.LetterID+1
and t1.ID = t2.ID
where t2.ID is null
and t1.LetterID>(select MIN(LetterID) from yourtable where ID = t1.ID)
于 2012-08-22T11:38:16.803 回答
0
;with cte as
(
  select max(LetterID) as id from your_table
  union all
  select id-1 from cte where id>1
)
select cte.id as LetterID
from cte
left join your_table yt on cte.id=yt.LetterID
where yt.id is null
order by cte.id
于 2012-08-22T12:05:33.827 回答
0

获取空白/缺失行

SELECT TOP 1 x.LetterID +1 
FROM tablename x
WHERE NOT EXISTS(SELECT * FROM tablename xx WHERE xx.LetterID  = x.LetterID  + 1)
ORDER BY x.LetterID
于 2012-08-22T13:27:52.053 回答