Firstly, you should be aware that this method of obtaining the autonumber value for the most recently added record only works reliably when evaluated within the scope of the same database workspace which created the record (when using DAO) or the same database connection (when using ADO). Evaluated independently of such connection, the statement will merely yield 0
.
Example
Say we have a table called Table1
with two fields:
Table1
+------------+--------+
| ID | Field1 |
+------------+--------+
| AutoNumber | Text |
+------------+--------+
We can create a new record using the following code:
With CurrentDb
.Execute "insert into table1 (field1) values ('abc')"
End With
If we want to find the value assigned to the AutoNumber field ID
, we can then do this:
With CurrentDb
.Execute "insert into table1 (field1) values ('abc')"
Debug.Print .OpenRecordset("select @@identity")(0)
End With
What is @@IDENTITY
?
Note that the SQL statement used in the above example is independent of any one particular table or field (there is no from
clause), as the @@identity
column merely refers to the last autonumber value issued (to any record within any table) for the current database workspace (DAO)/connection (ADO).
This T-SQL documentation may help with your understanding, but note that this applies to SQL Server, not MS Access, and so whilst this provides a description of the purpose of @@identity
, not everything will translate directly to MS Access.
How Does .OpenRecordset("...")(0)
Work?
As for the use of (0)
directly following the .OpenRecordset
method, this simply shorthand for accessing the first item in the Fields
collection (which is the default member of the Recordset class), and is therefore equivalent to:
.OpenRecordset("select @@identity").Fields(0)