2012-08-22 71 views
1

可能重复:
Find the smallest unused number in SQL Server获取丢失数

我有这样的表在SQL Server

ID | LetterID | LetterName 

ID => int和身份

LetterID => int和独特和从我的C#应用​​程序和用户设置数NOTNULL

LetterName =>串

LetterID填充为it.for例如1,2,3,4,5 ,. ..,100,..(每行增加一个单位)现在我的LetterID100但有时用户从表中删除一行,例如删除行,其中LetterID50,现在用于插入新行(在应用程序中)我建议他LetterID选择50,我如何从表格中找到缺失的数字?

+4

你为什么要弥补这些差距? –

+0

我们担心多用户和锁定在这里吗?即你是否必须从其他用户那里锁定50个? –

+1

你为什么要填补这些空白? - Tim Schmelter =>是 –

回答

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 
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) 
1
var output = Enumerable.Range(1, list.Max(item => item.LetterID)) 
      .Except(list.Select(item => item.LetterID)) 
+0

你能否请进一步解释这个来源? –

+0

此代码除了两个list.is代码优化为高排? –

+0

@hamidrezamansouri:此源使用LINQ to Entities –

0
​​