How to ignore some parameters in TQuery

741 views Asked by At

If i have a SQL statement like below

SELECT * FROM myTable WHERE CID = :vCID AND DataType = :vDataType

And usually i use TQuery to get some data like below

aQuery.ParamByName('vCID').Value := '0025';
aQuery.ParamByName('vDataType').AsInteger := 1;

But how can i ignore the "CID" key to get a SQL like

SELECT * FROM myTable WHERE DataType = :vDataType

I've try the below synctax, but failed

aQuery.ParamByName('vCID').Value := '%';
aQuery.ParamByName('vDataType').AsInteger := 1;

Please help me out, thank you.

3

There are 3 answers

0
Remy Lebeau On BEST ANSWER

The best option is to simply use separate queries:

aQueryBoth.SQL.Text := 'SELECT * FROM myTable WHERE CID = :vCID AND DataType = :vDataType';
...
aQueryBoth.ParamByName('vCID').Value := '0025';
aQueryBoth.ParamByName('vDataType').AsInteger := 1;

aQueryDataType.SQL.Text := 'SELECT * FROM myTable WHERE DataType = :vDataType';
...
aQueryDataType.ParamByName('vDataType').AsInteger := 1;
3
bummi On

Change your Query to

SELECT * FROM myTable 
WHERE CID = ISNULL(:vCID,CID) AND DataType = ISNULL(:vDataType,DataType)

or

SELECT * FROM myTable 
WHERE COALESCE(CID,'') = COALESCE(:vCID,CID,'') 
  AND COALESCE(DataType,0) = COALESCE(:vDataType,DataType,0)

The second one would handle the case of NULL values in the table too.

The Parameter you don't want to use can be set to Unassigned

aQuery.ParamByName('vCID').Value := Unassigned; // <<
aQuery.ParamByName('vDataType').AsInteger := 1;

Since :vCid is NULL it will be evaluated as CID = CID

0
Arioch 'The On

Usual but somewhat verbose way is to introduce yet another parameter.

SELECT * FROM myTable 
   WHERE ( ( CID = :vCID ) OR ( :IgnoreCID <> 0 )) 
     AND ( DataType = :vDataType )

Then turning your queries into

aQuery.ParamByName('vCID').Value := '0025';
aQuery.ParamByName('IgnoreCID').AsInteger := 0;
aQuery.ParamByName('vDataType').AsInteger := 1;

or

aQuery.ParamByName('vCID').Value := Unassigned;
aQuery.ParamByName('IgnoreCID').AsInteger := 1;
aQuery.ParamByName('vDataType').AsInteger := 1;

If the server has decent SQL Optimizer, then it would figure out when the 1st parameter is worth checking or not.