Search code examples
delphifiredac

How to delete all records matching a certain value in a FireDAC dataset?


I have a usual while not EOF do loop that deletes certain records from a memory table. Deleting the last record does not signal EOF as expected. Here's my code:

mtCt.First;  
while Not mtCt.Eof do  
begin  
  if mtCtAmt.Value = 0.0 then
    mtCt.Delete
  else
    mtCt.Next;  
end;

How can I delete all records matching a certain value in a FireDAC dataset?


Solution

  • This is normal behavior with all Delphi datasets.

    If your deleting logic is as simple as your example, you can simply ignore this, anyway the next iteration will not satisfy the deleting condition, issuing a Next and going EOF.

    If instead the logic is complex and you need to avoid the unnecessary iteration, you may use a trick like this:

    var
      PrevRecNo: Integer;
    begin
      mtCt.First;  
      while Not mtCt.Eof do  
      begin  
        if mtCtAmt.Value = 0.0 then
        begin
          // save the current record number 
          PrevRecNo := mtCt.RecNo;
    
          // delete will normally not change current record number
          // unless you've deleted the last record, in this case
          // the current record will be one less than before
          mtCt.Delete;
    
          // so, if the saved record number and the current one are
          // different, you've delete the last record, just issue a
          // Next in order to hit EOF and exit the while loop
          if mtCt.RecNo <> PrevRecNo then
            mtCt.Next;
        end
        else
          mtCt.Next;  
      end;