MS Access OpenRecordset query

只愿长相守 提交于 2020-01-22 02:32:07

问题


Using MS Access, when I want to know the ID of the most recently added record, I use

nNewID = CurrentDb.OpenRecordset("SELECT @@IDENTITY")(0)

which I picked up from a posting on StackOverflow.

Please can someone explain how this works? In particular, there doesn't seem to be any reference to the table that the record has been added to - so does @@IDENTITY refer to the last added record, whichever table it was added to? - also what is the role of the (0) at the end of the statement?

Thanks for your help


回答1:


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)


来源:https://stackoverflow.com/questions/59536648/ms-access-openrecordset-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!