I have a JET table with an auto-number as the primary key, and I would like to know how I can retrieve this number after inserting a row. I have thought of using MAX() to retrieve the row with the highest value, but am not sure how reliable this would be. Some sample code:
Dim query As String
Dim newRow As Integer
query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
newRow = CurrentDb.Execute(query)
Now I know that this wouldn’t work, since Execute() won’t return the value of the primary key, but this is basically the kind of code I am looking for. I will need to use the primary key of the new row to update a number of rows in another table.
What would be the simplest / most readable way of doing this?
If
DAOuseIf
ADOusecnbeing a valid ADO connection,@@Identitywill return the lastIdentity(Autonumber) inserted on this connection.Note that
@@Identitymight be troublesome because the last generated value may not be the one you are interested in. For the Access database engine, consider aVIEWthat joins two tables, both of which have theIDENTITYproperty, and youINSERT INTOtheVIEW. For SQL Server, consider if there are triggers that in turn insert records into another table that also has theIDENTITYproperty.BTW
DMaxwould not work as if someone else inserts a record just after you’ve inserted one but before yourDmaxfunction finishes excecuting, then you would get their record.