Visit our Sponsor   Visit our Sponsor
delphi3000.com - the free delphi knowledge platform
delphi3000.com - the free delphi knowledge platform
Have a look at your member-status

connecting people's knowledge


  - Recent ArticlesRSS feed for Recent Articles on delphi3000.com
  - List of All Articles
  - Top Viewed Articles
  - Articles (+Attachem.)
  - Articles Of Interest
  - Categories
  - Top Uploader
  - Search
  - Index

  - My Home
  - Submit an Article
  - My Articles
  - My Personal Data
  - My Bookmarks
  - Activities
  - Login/Logout

  - Sign Up
  - Why Sign Up
  - Newsletter

  - Press
  - Advertise

  - Contact
  - Feedback





Community
Borland
ClubeDelphi
Dr. Bob
UK-BUG
Delphi Meetings
Planeta Delphi







Startblatt.de






Share this article with friendsShare this article with friends
Rate this articleRate this article - to keep the quality of delphi3000.com !
Comment this article or read through previous comments (10)


Ms Access LastinsertIDGo to Ronald Buster's websiteFormat this article printer-friendly!Bookmark function is only available for registered users!
Product:
Delphi 5.x (or higher)
Category:
ADO/OLE-DB
Skill Level:
Scoring:
Last Update:
03/28/2003
Search Keys:
delphi delphi3000 article borland vcl code-snippet database sql ado access microsoft windows query autoinc
Times Scored:
8
Visits:
10002
Uploader: Ronald Buster
Company: DISPI software Engineering
Reference: http://www.dispi.com
 
Question/Problem/Abstract:
Ever wondered how to retrieve the last insert id in MsAccess, of the autoincrement field from a table.
Answer:



We have a table in MsAccess like :

Test, Fields (id=autoinc, name=text);

First we have to have a function like the one below :

function GetLastInsertID : integer;
begin

  // datResult = TADODataSet

  datResult.Active := False;
  datResult.CommandText := 'select @@IDENTITY as [ID]';
  datResult.Active := True;

  Result := datResult.FieldByName('id').AsInteger;

  datResult.Active := False;

end;

Now before getting the last inserted record record id = autoincrement field, in other words calling the above function. You have to do a SQL insert like the following

procedure InsertRec;
begin
  
  // datCommand = TADOCommand

  datCommand.CommandText := 'insert into [test] ( [name] ) values ( "Test" )';
  datCommand.Execute;

end;

Now if we like to know which is the last autoinc value ( notice that the getlastinsertid proc. only works after the insertrec proc)


procedure Test;
begin
  InsertRec;
  Showmessage(format('lastinsertid : %d',[GetLastInsertID]));
end;

Hope you can make this work, it works for me, any questions feel free to ask

Ronald





Please rate this article!
Skill level:
BeginnerExpert

Useful:
No!Very!

Overall rating:
PoorExcellent



Comments to this article
Write a new comment
Results 0
    Eduardo T Quadrado (Nov 27 2004 2:16PM)

I tried use and it results 0.

How I must configure de ADODataSet ?
- cmdType

Is it works with all versions of Access ?
- I'm using Access 97

If I make the Insert inside a Transaction, any problem ?

Thanks.

Eduardo
Respond

Multiuser considerations?
    Doug Chamberlin (Apr 3 2003 1:02PM)

How can this possibly work in a multi-user environment? What if another user inserts a record after you do but before you call your function to get the last ID value?

Since you are calling the database twice anyway, why not call first to get a new ID value and then call again to use it in the INSERT statement. That way you know what value you actually used in your INSERT.
Respond

RE: Multiuser considerations?
Ronald Buster (Apr 3 2003 1:13PM)

This works excellent in a multiuser environment using MsAccess, but it works a bit different then you think. We use this in all our apps running with MsAccess as a database.

The function GetLastInsertID only works after you have inserted a new record and only gives the lastinsertID of the TABLE where you inserted the new record.

If you call the function GetLastInsertID before you want to insert a new record it does not work you got a -1 value.

According to Microsoft Technical Docs this works correctly and can only be used when using SQL to insert a new record and only after you insert a new record.

If you have any questions please feel free to ask ok.

Ronald
Respond

RE: Multiuser considerations?
Doug Chamberlin (Apr 3 2003 5:50PM)

So if 1) I add a record and then 2) you add a record and then 3) I inquire what the last ID value inserted was will I get back the ID value that was used in my record or the one used in your record?
Respond

RE: RE: Multiuser considerations?
Ronald Buster (Apr 3 2003 6:16PM)

Consider the following :

there are 4 users in our network and you are user 4
the table is called TEST

user 1 inserts 1 record
user 2 inserts 1 record
user 3 inserts 1 record

you  user 4 inserts a record and after that when I call the GetLastinsertID function the result value is the value of the record
I have inserted. So the unique id my last inserted record has in table TEST for user 3 this is the value of his last inserted record.

So it doesn't matter if I am user 1 or 2 or 3 or 4 after I insert a record I always get the last insertid (read unique id of the autoinc field) in the TABLE TEST.

You have to play a little bit with it and then you can see that it works.

Regards,

Ronald






Respond

RE: Multiuser considerations?
Doug Chamberlin (Apr 4 2003 4:45AM)

Oh, I have no doubt that what you claim is true. However, I find it trivial.

What I thought you were solving was the problem of inserting a record into a table which has an auto-incrementing field and then needing to obtain the auto-increment value that was used for that record. (Not the last value added by just anyone.) This is often needed if you want to subsequently retrieve the record you inserted.

I don't know why anyone would want to know auto-increment value last used by anyone. What use it that?
Respond

RE: RE: Multiuser considerations?
anonymus (Apr 4 2003 10:14AM)

Here's what you say :

"What I thought you were solving was the problem of inserting a record into a table which has an auto-incrementing field and then needing to obtain the auto-increment value that was used for that record. (Not the last value added by just anyone.) This is often needed if you want to subsequently retrieve the record you inserted."

The function GetLastInsertID does the trick you describe above.

It does not and I repeat not returns the last value added by just anyone, because the function works only after I have inserted a record it otherwise you get a -1 value. So it only returns the autoinc field value of the last inserted record you as user did and it does NOT return the last inserted autoinc value from another user.

Start playing with it make a small delphi app and test it you will see it does just the job for you.

We use this alot considering the following

table : customer

id - autoinc
name - text

When I insert a new record in table customer and I need to know what is the value of the ID (autoinc) field of my newly inserted record. I do that bij calling GetLastInsertID this function returns the value of the ID field of my inserted record.

When you make a database connection with a MsAccess database then you get your own workspace from access consider this as a session. When calling GetLastInsertID you get the value of your latest inserted record and NOT I REPEAT NOT GET IT FROM ANOTHER USER.

Regards,

Ronald



Respond

RE: Multiuser considerations?
Doug Chamberlin (Apr 4 2003 2:14PM)

OK, I understand now. You are pointing out that @@IDENTITY is implemented and documented to do exactly what I was looking for and your tip shows one way to use it.
Respond

Big Question?
Edwin Okugbo (May 3 2003 10:16PM)

Do you guys think this will work for MS SQL server?
Respond

RE: Big Question?
Ronald Buster (May 5 2003 10:56AM)

I might work on ms sqlserver however you need to know what the corresponding SQL statement is for retrieving the last autoinc value for a table after an insert like :

datResult.CommandText := 'select @@IDENTITY as [ID]';

I know the same thing we use for MySQL server and then the SQL statement is :

datResult.CommandText := 'select lastinsertid() as [ID]';

So you have to find out what that SQL statement for MS SqlServer is !
Respond














 
Sign up to consume product discounts for Bronze memberships !

read more


  Visit our Sponsor

 

  Community Ad of
D. Souchard
 
   














 







     
  Copyright © 2000 - 2007 delphi3000.com - All rights reserved. Terms of use. || Privacy
delphi3000.com is a service by bluestep.com IT-Services GmbH (Vienna)