Delphi -

How to get the auto incremented primary key value of the last inserted record


procedure TForm1.MyButtonClick(Sender: TObject);
var
   
My_Key_Value:integer;
    temp_query: TADOQuery;
begin
    MyADOTable.Insert;
    MyADOTable.FieldByName('CustomerFirstName').AsString := 'Jim';
    MyADOTable.FieldByName('CustomerLastName').AsString := 'Jones';
    MyADOTable.Post;

    // get the Primary key value of the last inserted record
    temp_query:=tadoquery.Create(nil);
    temp_query.Connection:=ADOConnection1; // the same connection as MyADOTable
    // put the number in an alias name
    temp_query.SQL.Text:='select @@IDENTITY as MyKeyValue';
    temp_query.Active:=true;
    // now we can read it
    My_Key_Value:=tt.FieldByName('MyKeyValue').AsInteger;
    temp_query.free;


    // now we can do something with the number
    MyOtherTable.Edit;
    MyOtherTable.FieldByName('t_link').AsInteger:=My_Key_Value;
    MyOtherTable.Post;
end;