问题
I am busy with a school project where I query a database based on a server from a client. One of the requirements is to retrieve the next available AutoNumber
from the database.
What would the SQL query be to retrieve the next available Autonumber
? Is it possible to do this?
回答1:
It depends on the flavor of the RDBMS. MariaDB (MySQL) have LAST_INSERT_ID() function which gives you the last value of an AUTO_INCREMENT field.
Databases that support sequences (say Ingres) allow you to get next value with something like:
SELECT NEXT VALUE FOR some_sequence;
or
SELECT some_sequence.NEXTVAL;
回答2:
The next autonumber is not the same as the last autonumber +1. If records have been deleted, the next possible autonumber could be considerably higher that the last number. It is also possible to get negative autonumbers with MS Access. As Allen Browne shows, you can use ADOX to get the seed property of the autonumber column, which is the next autonumber.
回答3:
If it's Oracle, then run the below query using JDBC
SELECT YOUR_SEQUENCE.NEXTVAL FROM DUAL
回答4:
The best solution is to insert a record, then get generated keys, and then rollback the transaction. It works on all databases with transaction and auto-number support.
来源:https://stackoverflow.com/questions/9554857/retrieving-next-available-autonumber