How do we get last inserted record in msaccess query

感情迁移 提交于 2021-02-08 09:53:45

问题


I am inserting data from my vb.net application to msaccess db.

I am confused in way of getting the last inserted record added to a table. IN MS-SQL we get @@IDENTITY for that but it didn't worked for me in MSAccess.

so what should be do for getting the last inserted record added to a table?


回答1:


Example:

Dim db As Database
Set db = CurrentDb

db.Execute "INSERT INTO Table1 (atext) Values('abc')", dbFailOnError

Dim rs As dao.Recordset

Set rs = db.OpenRecordset("select @@identity")
Debug.Print rs(0)

It does require that there is an autoincrement key on the table.




回答2:


It's more complicated in Access than SQL Server because access doesn't support the execution of multiple statements in a batch or output parameters.

According to the MSDN documentation, you need to add a handler for the RowUpdated event.

Before resorting to this, however, I would try wrapping your insert code in a transaction and then executing the select @@identity method within the transaction. Might not work, but worth a shot.




回答3:


As far as I know, MS Access does not have the functionality to get the last added row.

In practice, I create an autoincrement column (which is usually the Primary Key anyway). Then I run this query when I desire to get the last row in the table:

SELECT TOP 1 * FROM [Table] ORDER BY [IdColumn] DESC

It simply sorts the the rows in the table by the ID column in reverse order and takes the first one (which is really the last row in the table).




回答4:


It's always a good practice to have a numeric (even auto-increment) primary key. Then you can always select the MAX and that's the latest inserted record.



来源:https://stackoverflow.com/questions/8533283/how-do-we-get-last-inserted-record-in-msaccess-query

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