Getting the Value of an Auto-Increment Field


Say you inserted a new record into the customer table, and did not assign a value to the customer_id field, because this field is an auto-increment field. In many applications, after a record is inserted, it will be important to know what value the database engine assigned to the auto-increment field (note that a table can only have a single auto-increment field). The technique used to find the value of the auto-increment field varies depending on the type of back-end database that you are using. In the following example, we use a technique that works with SQL Server, Access, and MySQL. It may also work with some other databases, but certainly will not work will all databases. You will need to refer to the documentation for your database to see what method they use.

To get the value of auto-increment field, we execute a special query:

select @@identity

First, dim the variables.

dim conn as SQL::Connection
dim sql_insert as C
dim qry as C
dim auto_number as N

Define the SQL queries.

sql_insert = "insert into customer (firstname, lastname, bill_city, bill_postal_code, bill_state_region) values ('George', 'Jones', 'Arlington', '02000', 'VA')"
qry = "select @@identity"

Open the connection and add a record.

?"{A5API=Access,FileName='C:\Program Files\a5v8\MDBFiles\Alphasports.mdb',UserName='Admin'}")
= .T.

Get the auto-increment number of the new record.

auto_number =
ui_msg_box("Autoincrement Number", "" + auto_number)

Executing the query select @@identity returns a result set with one row and one column containing the value of the auto-increment field. In this case the value is above 60 (depending on how many times you ran the script), which is the customer_id for the new record that we added.


Desktop applications only.

See Also