Page 1 of 1

TMyQuery and ParamByName

Posted: Sun 14 Feb 2021 18:26
by alphawiz1
I'm trying to build a dynamic query where the user can select the field as part of the search.

My question is can I do this by using ParamByName?

Example :
MyQuery1.SQL := 'select * from mytable where :field = :value;'
MyQuery1.ParamByName('field').AsString := 'fieldname';
MyQuery1.ParamByName('value').AsString := 'myvalue';
MyQuery1.Execute;

The test didn't return any errors but it didn't return any results either when I reference MyQuery1.RecordCount , so I'm guessing it doesn't necessarily work this way, but if it does, what am I doing wrong? Or is there an easier way to do it? If so, could an example be provided?

Re: TMyQuery and ParamByName

Posted: Mon 15 Feb 2021 07:33
by hkarmeh
Try

MyQuery1.SQL := 'select * from mytable where &field = :value;

MyQuery1.MacroByName('field').AsString := 'fieldname';
MyQuery1.ParamByName('value').AsString := 'myvalue';
MyQuery1.Execute;

Re: TMyQuery and ParamByName

Posted: Mon 15 Feb 2021 09:59
by ViktorV
alphawiz1 wrote: Sun 14 Feb 2021 18:26 I'm trying to build a dynamic query where the user can select the field as part of the search.

My question is can I do this by using ParamByName?

Example :
MyQuery1.SQL.Text := 'select * from mytable where :field = :value;'
MyQuery1.ParamByName('field').AsString := 'fieldname';
MyQuery1.ParamByName('value').AsString := 'myvalue';
MyQuery1.Execute;

The test didn't return any errors but it didn't return any results either when I reference MyQuery1.RecordCount , so I'm guessing it doesn't necessarily work this way, but if it does, what am I doing wrong? Or is there an easier way to do it? If so, could an example be provided?
As hkarmeh wrote correctly to solve the issue, you can use Macros. For example:

Code: Select all

  MyQuery1.SQL := 'select * from mytable where &field = :value;'
  MyQuery1.MacroByName('field').Value := 'fieldname'; //If you set macro with the AsString property, it will be quoted. 
  MyQuery1.ParamByName('value').AsString := 'myvalue';
  MyQuery1.Execute;
You can learn more about Macros at: http://www.devart.com/mydac/docs/work_macros.htm