首页  编辑  

获取ADO最后插入的记录的记录ID

Tags: /超级猛料/Database.数据库相关/ODBC、ADO、Access/   Date Created:

获取ADO最后插入的记录的记录ID

recover the ID of the last inserted row in a table (ADO)?

// Insert a new Record...

var

 LastID: Integer;

//  Query: TADOQuery;

//  oder

//  Query: TQuery;

begin

 Query.Active := False;

 Query.SQL.Clear;

 Query.SQL.Append('INSERT INTO Table (Spalte) VALUES (Value)');

 Query.ExecSQL;

 LastID := GetLastID(Query);

end;

// get the ID of the last inserted row

function GetLastID(var Query: TADOQuery {or TQuery}): Integer;

begin

 result := -1;

 try

   Query.SQL.clear;

   Query.SQL.Add('SELECT @@IDENTITY');

   Query.Active := True;

   Query.First;

   result := Query.Fields.Fields[0].AsInteger;

 finally

   Query.Active := False;

   Query.SQL.clear;

 end;

end;