Fabio
Fabio

Reputation: 93

Insert field name in Delphi SQL parameter instead of string

I have written an SQL query in delphi that has a parameter

WHERE L1.IdListino = :IdListino

Based on some input from the user, I want this parameter to be either a field of a form (tParsIdListinoExport is the name of the field), or a column of another table (something like WHERE L1.IdListino = fat.IdListino).

if tParsIdListinoExport.AsString <> '' then
        qSel.ParamByName( 'IdListino' ).AsString := tParsIdListinoExport.AsString
    else
        qSel.ParamByName( 'IdListino' ).Value := 'fat.IdListino';
end;

Sadly, looks like I can't insert a column name as a parameter, because it adds the '' around the name of the column, thus treating it as plain text. Is it possible to remove the '' from the parameter? Thank you very much,

Fabio

Upvotes: 1

Views: 1480

Answers (2)

Hugh Jones
Hugh Jones

Reputation: 2694

You might be able to achieve what you need with sql. The details are a little dependent upon the RDBMS but something along the lines of

where (:param1 = 'use_field' and :param2 = OtherTable.field) or (:param1 = 'use_param' and Table.field = :param3)

This assumes that Table and OtherTable are joined. It also assumes Param1 can be mentioned more than once - not all databases will allow this.

Upvotes: 0

Rafael Rossi
Rafael Rossi

Reputation: 88

You need create your SQL Instruction in runtime, like:

with qSel do
begin
    Close;
    SQL.Clear;
    SQL.Add(addYourSqlHere, without Where clause);
    if Condition1 then
        SQL.Add('where FIELD1 = :PARAM01')
    else
        SQL.Add('where FIELD2 = :PARAM01');
    ParamByName('PARAM01').Value := UserFilter;
end;

Upvotes: 3

Related Questions