开发者

Get last insert ID from Access

I am familiar with the MySQL function LAST_INSERT_ID; is there a similar function for performing the same query with a MS Access database via ODBC?

In my specific case, I am using PHP+PDO to insert rows into an Access database, and would like to know the last primary key value of each insert as they are performed.

If this functi开发者_运维技巧onality is not available, are there any alternatives? (without changing the database)

Thank you.


It seems that Access 2000 or later supports the @@IDENTITY property. So, you would only need to select its value after an INSERT:

select @@IDENTITY from myTable

Please see the MSDN link: Retrieving Identity or Autonumber Values

In short:

[...] Microsoft Access 2000 or later does support the @@IDENTITY property to retrieve the value of an Autonumber field after an INSERT. Using the RowUpdated event, you can determine if an INSERT has occurred, retrieve the latest @@IDENTITY value, and place that in the identity column of the local table in the DataSet.


As others have said, SELECT @@IDENTITY works with Jet 4 and the ACE.

A new consideration has been introduced with Access 2010, and that's because the new ACE version supports table-level data macros, which are the equivalent of triggers. Thus, an insert in one table might trigger an insert in another, so that @@IDENTITY might be the value for the second table instead of the top-level one. So far as I know, there is no equivalent to SQL Server's SCOPE_IDENTITY() for this scenario.

I have asked about it in other Access forums and nobody seems to know. It's something to watch for should you be using an ACCDB with table-level data macros.


I've never attempted to use access with php, but two ideas come to mind, The first one is simple. And that's to simple select max(id) from table after your insert, since it is auto incrementing you will get the highest value which should be the insertted value. Secondly you can try using odbc_cursor (http://au2.php.net/manual/en/function.odbc-cursor.php).


Try running "SELECT @@IDENTITY FROM MyTable" after your insert.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜