Recent

Author Topic: How to get last record ID from database table  (Read 6981 times)

fiazhnd

  • New Member
  • *
  • Posts: 36
How to get last record ID from database table
« on: August 05, 2017, 04:57:10 pm »
I am using Delphi and want to get last record id (SerID)(PK-autonumber) value and increment by 1 and assign to EditServicesID. i am using the following code but now a success at all.
Code: Pascal  [Select][+][-]
  1. EditServiceID.Text:=IntToStr(ADOQueryCCA.SQL.ADD('Select SerID from tcustomercaractivity ORDER BY SerID DESC LIMIT 1')+1);
Code: Pascal  [Select][+][-]
  1. EditServiceID.Text:=IntToStr(ADOQueryCCA.SQL.ADD('Select Last(SerID) From tcustomercaractivity')+1);
  2.  
Code: Pascal  [Select][+][-]
  1. EditServiceID.Text:=IntToStr(ADOQueryCCA.SQL.ADD('Select Max(SerID) From tcustomercaractivity')+1);
  2.  
Any Suggestion
« Last Edit: August 05, 2017, 05:04:52 pm by fiazhnd »

mangakissa

  • Hero Member
  • *****
  • Posts: 1131
Re: How to get last record ID from database table
« Reply #1 on: August 05, 2017, 05:42:04 pm »
This is not a Delphi forum.
Also more info is welcome.
Databaase?
Lazarus 2.06 (64b) / FPC 3.0.4 / Windows 10
stucked on Delphi 10.3.1

fiazhnd

  • New Member
  • *
  • Posts: 36
Re: How to get last record ID from database table
« Reply #2 on: August 05, 2017, 05:47:52 pm »
MS Access

shobits1

  • Sr. Member
  • ****
  • Posts: 271
  • .
Re: How to get last record ID from database table
« Reply #3 on: August 07, 2017, 12:24:25 am »
This may not work,  since I don't have Delphi.

anyway try this:

Code: Pascal  [Select][+][-]
  1. function GetLastID(var aQuery: TADOQuery; const aField: string; const aTable: string): Integer;
  2. begin
  3.   result := -1;
  4.  
  5.   if (aField = '') or (aTable = '') then
  6.     Exit;
  7.  
  8.   try
  9.     aQuery.Active := False; // or aQuery.Close;
  10.     aQuery.SQL.clear;
  11.     aQuery.SQL.Add('Select Last('+aField+') FROM ' + aTable);
  12.     aQuery.Active := True; // or aQuery.Open;
  13.     aQuery.First;
  14.     result := aQuery.Fields.Fields[0].AsInteger;
  15.   finally
  16.     aQuery.Active := False;
  17.     aQuery.SQL.clear;
  18.   end;
  19. end;
  20.  
  21. {
  22. .
  23. .
  24. .
  25. YOUR CODE
  26. .
  27. .
  28. .
  29. }
  30.  
  31. var
  32.   LastID: Integer;
  33. begin
  34.   LastID := GetLastID(ADOQueryCCA, 'SerID', 'tcustomercaractivity');
  35.  
  36.   if LastID < 0 then
  37.     EditServiceID.Text:='No record found'
  38.   else
  39.     EditServiceID.Text:=IntToStr(LastID+1);
  40. end;
  41.  
  42.  

mangakissa

  • Hero Member
  • *****
  • Posts: 1131
Lazarus 2.06 (64b) / FPC 3.0.4 / Windows 10
stucked on Delphi 10.3.1

 

TinyPortal © 2005-2018