1

Possible Duplicate:
Find the smallest unused number in SQL Server

I have this table in Sql server

ID |  LetterID | LetterName

ID => int and identity

LetterID => int and unique and NotNull

LetterName => string

LetterID fill from my C# application and user set number for it.for example 1,2,3,4,5,...,100,.. (increment an unit for each row) and now my LetterID is 100 but Sometimes user delete one row from table for example delete row where LetterID is 50, now for insert new row (in application) I suggested to him LetterID chose 50, How can I get the missing numbers from table?

Community
  • 1
  • 1
hamid reza mansouri
  • 11,035
  • 2
  • 22
  • 32

4 Answers4

1
var output =  Enumerable.Range(1, list.Max(item => item.LetterID))
          .Except(list.Select(item => item.LetterID))
cuongle
  • 74,024
  • 28
  • 151
  • 206
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)
podiluska
  • 50,950
  • 7
  • 98
  • 104
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
Dumitrescu Bogdan
  • 7,127
  • 2
  • 23
  • 31
0

get the blank/missing row

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
NG.
  • 5,695
  • 2
  • 19
  • 30