|
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: 9387 | 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
|
|