7

I would like to expose a function that can take an optional anonymous method :

    type
      TParamsProc = reference to procedure(Params: TSQLParams);
      TFieldsProc = reference to procedure(Fields: TSQLResult);

      TDbController = class
        ...
      public
        procedure Select(const SQL: sting; ParamsProc: TParamsProc; FieldsProc: TFieldsProc);
      end;

    implementation

    procedure TDbController.Select(const SQL: sting; ParamsProc: TParamsProc; FieldsProc: TFieldsProc);
    var
      Q: TUIBQuery;
    begin
      Q := TUIBQuery.Create(nil);
      try
        Q.Database := FDatabase;
        Q.Transaction := FTransaction;
        Q.SQL.Text := SQL;
        ParamsProc(Q.Params);
        Q.Open;
        while not Q.Eof do
        begin
          FieldsProc(Q.Result);
          Q.Next;
        end;
      finally
        Q.Free;
      end;
    end;

As sometimes I have no params to pass to a SQL Query, I would like to make the ParamsProc optional.

this code don't work :

      if ParamsProc <> nil then ParamsProc(Q.Params);

nor this one :

      if @ParamsProc <> nil then ParamsProc(Q.Params);

The first one don't compile, the second one compile but don't work because ParamsProc has always a non nil value.

Example of call :

      FController.Select(
        'select A, B, C from SOME_TABLE', 
        nil, 
        procedure(Fields: TSQLResult)
        begin
          FA := Fields.AsInteger[0];
          FB := Fields.AsString[1];
          FC := Fields.AsCurrency[2];
        end
      );

Edit

Seems that Assigned(ParamsProc) do the trick.

Robert Love
  • 12,447
  • 2
  • 48
  • 80
ZeDalaye
  • 689
  • 7
  • 17
  • 4
    @ZeDelaye make your edit an answer (if possible: with sample source), then you can accept the answer, and people can vote for it. I'd vote, as it is a good solution for an area of which Delphi documentation is 'poor'. – Jeroen Wiert Pluimers May 02 '11 at 19:31

1 Answers1

1

Following Jeroen Pluimers advice, I make my "Edit" an "Answer" :

Assigned(ParamsProc) do the trick :

procedure TDbController.Select(const SQL: sting; ParamsProc: TParamsProc; FieldsProc: TFieldsProc);
var
  Q: TUIBQuery;
begin
  Q := TUIBQuery.Create(nil);
  try
    Q.Database := FDatabase;
    Q.Transaction := FTransaction;
    Q.SQL.Text := SQL;
    if Assigned(ParamsProc) then
      ParamsProc(Q.Params);
    Q.Open;
    while not Q.Eof do
    begin
      FieldsProc(Q.Result);
      Q.Next;
    end;
  finally
    Q.Free;
  end;
end;

Hope this helps !

ZeDalaye
  • 689
  • 7
  • 17