Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Smallest positive number not already used. 1

Status
Not open for further replies.

donutman

Programmer
Dec 20, 2002
2,481
US
What's a "good" way to obtain the smallest positive number not already used within a particular integer field of a table? I'm running MS SQL Server.
 
select min(i+1)
from tbl t1
where not exists (select * from tbl t2 where t1.i = t2.i+1)

select top 1 t1.i+1
from tbl t1
left join tbl t2
on t1.i = t2.i+1
where t2.i is null
order by t1.i

======================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
 
A slight typo in nigelrivett's solution. It should read:

select top 1 t1.i+1
from tbl t1
left join tbl t2
on t1.i+1 = t2.i
where t2.i is null
order by t1.i
 
Oops - thanks

======================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
 
why not just

select max(i)+1 from tbl

if tbl is big and there is an index on the i column, then this might be quicker:

select top 1 i + 1 from tbl
order by i

Regards to all,
Emblem
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top