简体   繁体   English

(VB.NET 2010)如何编写选择最小未使用编号的SQL查询

[英](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. 我正在尝试编写一种算法,该算法在运行时将遍历我的访问数据库中的一个表,并找到未使用的最低编号(=> 1)。 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. 为了澄清起见,这将是记录的ID,并且如果我在access中使用自动编号功能,则无法执行所需的任务。

For example, if I have records with IDs of 1 and 3; 例如,如果我有ID为1和3的记录; the algorithm will detect that "2" and will then return a value of 2 which I will be able to use later. 该算法将检测到“ 2”,然后返回值2,我以后可以使用它。

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. 不幸的是,我没有任何示例代码可以使用,但是我正在使用Microsoft Visual Studio 2010,并且我正在使用Oledb系统在VB.NET中进行编程以提供与数据库的连接。

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. 编辑:我正在考虑使用SORT查询,但我不知道该如何跟进。 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. 我想通过这样做,我可以让用户自己找到一个ID,然后进行设置,但这样做可能违背我的应用程序提供跟踪学生数据的自动系统的目的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM