2012-08-22 133 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
​​