What is the pkey of an INSERT into an autonumber?

M

Maury Markowitz

Is there some way to find out the pkey generated by an autonumber after
INSERTing into that table? I need to insert a record and then SELECT a few
fields from it, but I have no idea what the pkey is so I don't know who to
select against.

Does INSERT return a handle, or is there somewhere I can look to find this
number?
 
A

Allen Browne

In Access 2000 and later, you can use @@IDENTITY to get the primary key
value last inserted.

Example:
Function ShowIdentity() As Variant
Dim db As DAO.Database
Dim rs As DAO.Recordset

Set db = DBEngine(0)(0)
db.Execute "INSERT INTO MyTable ( MyField ) SELECT 'nuffin' AS Expr1;"

Set rs = db.OpenRecordset("SELECT @@IDENTITY AS LastID;")
ShowIdentity = rs!LastID
rs.Close

Set rs = Nothing
Set db = Nothing
End Function

The alternative is to open a recordset and use AddNew and Update. The
recordset then knows about the new record, so you can get the primary key
value.

--
Allen Browne - Microsoft MVP. Perth, Western Australia.

Reply to group, rather than allenbrowne at mvps dot org.

message
news:[email protected]...
 
V

Van T. Dinh

If you post questions in these newsgroups, you should specify that you use
MS SQL Back-End. Otherwise, almost all replies will assume JET Back-End and
the answers apply to JET and not necessarily MS SQL.

In fact, you even used Access terminology "AutoNumber" (MS SQL Server uses
"Identity").
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top