Search code examples
sqlvb.netms-accessoledbvb.net-2010

(VB.NET 2010) How to write an SQL query which selects the lowest unused number


I am trying to write an algorithm which, when run, will go through a table in my access database and find the lowest number (=> 1) that is unused. For clarification, this is to be an ID for records and I can't perform the tasks I will need to if I use the Autonumber function inside access.

For example, if I have records with IDs of 1 and 3; the algorithm will detect that "2" and will then return a value of 2 which I will be able to use later.

Unfortunately I don't have any example code which I can put up, but I am using Microsoft Visual Studio 2010 and I am programming in VB.NET with the Oledb system to provide a connection with my database.

Thank you for any help.

EDIT: I was considering using a SORT query but I don't know what I would follow it up with. So while it would be very rudimentary thus far, I could begin the algorithm with:

SELECT StudentID FROM Students
ORDER BY StudentID;

I suppose that by doing this I could get the user to find an ID themselves and then set it, but it may defeat the purpose of my application to provide an automated system for tracking student data.


Solution

  • select min(StudentID) + 1
    from Students s1
    where not exists (select 1 from Students s2
                      where s2.StudentID = s1.StudentID + 1)