Search code examples
delphiadodelphi-xe4

How can I get the number of deleted records?


I tried this:

function TMyClass.removeRecords(...) : integer;
var
  aC : TADOCommand;
  aRS : _RecordSet;
begin
  aC := createADOCommand;
  try
    aC.Connection := fConnection;
    aC.commandText := getDeleteModelSQLCommand( ... );
    aRS := aC.Execute;
    {$ifdef debug_AlwaysOne}
      result := 1;
    {$else}
      result := aRS.RecordCount;
    {$endif}
  finally
    releaseADOCommand( aC );
  end;
end;

It runs correctly with the debug_AlwaysOne conditional defined.

However, at the line that reads the RecordCount, it raises an error:

Operation is not allowed when the object is closed

Is there any way to get the number of removed records? I know I can execute an aggregate query before deletion. But can I do this without another SQL command call?


Solution

  • Use the overloaded version of TADOCommand.Execute() that has a RecordsEffected output parameter:

    function Execute(var RecordsAffected: Integer; const Parameters: OleVariant): _Recordset; overload;
    

    For example:

    function TMyClass.removeRecords(...) : integer;
    var
      aC : TADOCommand;
    begin
      aC := createADOCommand;
      try
        aC.Connection := fConnection;
        aC.commandText := getDeleteModelSQLCommand( ... );
        {$ifdef debug_AlwaysOne}
        aC.Execute;
        Result := 1;
        {$else}
        aC.Execute(Result, EmptyParam);
        {$endif}
      finally
        releaseADOCommand( aC );
      end;
    end;