This is a discussion on Query problem within the SQL Server forums, part of the Microsoft SQL Server category; --> Hi all, I am trying to write a query to do the following in SQL server but am struggling: ...
| |||||||
| Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| ||||
| Hi all, I am trying to write a query to do the following in SQL server but am struggling: I have a table with a int number field in it and I want to find out the lowest unused number in the table. Unfortunately, the numbers are not necesarily sequential (due to deletes). So I may have the following records: num ---- 1 2 3 4 6 8 9 10 I want a query to return me the value 5 - i.e. the lowest unused int in the table (assuming counting starts at 1). I know I could do this using a temporary table containing a full sequence of possible numbers (given some ceiling) using something like: select min(num) from temptable where num not in (select num from maintable) This would however mean creating a temporary table which I am trying to avoid. I could also use a cursor to itterate through the records above to find the lowest unused number but it seems overkill. I'm sure there must be a way of doing this using a simple (possibly nested) query. Any ideas? Thanks in advance --James |