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?
In your example, because you use CurrentDB to execute your INSERT you've made it harder for yourself. Instead, this will work:
I used to add by opening an
AddOnly
recordset and picking up the ID from there, but this here is a lot more efficient. And note that it doesn't requireADO
.This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.
LeCygne
If
DAO
useIf
ADO
usecn
being a valid ADO connection,@@Identity
will return the lastIdentity
(Autonumber) inserted on this connection.Note that
@@Identity
might be troublesome because the last generated value may not be the one you are interested in. For the Access database engine, consider aVIEW
that joins two tables, both of which have theIDENTITY
property, and youINSERT INTO
theVIEW
. For SQL Server, consider if there are triggers that in turn insert records into another table that also has theIDENTITY
property.BTW
DMax
would not work as if someone else inserts a record just after you've inserted one but before yourDmax
function finishes excecuting, then you would get their record.