Supplying Parameters at Runtime
Go Up to Using Parameters in Queries
To create parameters at run time, you can use the
- ParamByName method to assign values to a parameter based on its name (not available for TADOQuery)
- Params or Parameters property to assign values to a parameter based on the parameter's ordinal position within the SQL statement.
- Params.ParamValues or Parameters.ParamValues property to assign values to one or more parameters in a single command line, based on the name of each parameter set.
The following code uses ParamByName to assign the text of an edit box to the :Capital parameter:
SQLQuery1.ParamByName('Capital').AsString := Edit1.Text;
SQLQuery1->ParamByName("Capital")->AsString = Edit1->Text;
The same code can be rewritten using the Params property, using an index of 0 (assuming the :Capital parameter is the first parameter in the SQL statement):
SQLQuery1.Params[0].AsString := Edit1.Text;
SQLQuery1->Params->Items[0]->AsString = Edit1->Text;
The command line below sets three parameters at once, using the Params.ParamValues property:
Query1.Params.ParamValues['Name;Capital;Continent'] := VarArrayOf([Edit1.Text, Edit2.Text, Edit3.Text]);
Query1->Params->ParamValues["Name;Capital;Continent"] = VarArrayOf(OPENARRAY(Variant, (Edit1->Text, Edit2->Text, Edit3->Text)));
Note that ParamValues uses Variants, avoiding the need to cast values.