I'm running an IB database interfacing through FireDAC.
The following dynamic query works :
INSERT INTO RELATIONS (C_ID, M_ID, A_ID)
SELECT c.C_ID, 0, a.A_ID
FROM CATEGORIES c, ACTIONS a
WHERE c.NAME = :CATEGORY AND a.NAME = :ACTION
I add a column to RELATIONS A_INDEX(Integer). For this column I want to supply a parameter so I do this:
INSERT INTO RELATIONS (C_ID, M_ID, A_ID, A_INDEX)
SELECT c.C_ID, 0, a.A_ID, :A_INDEX
FROM CATEGORIES c, ACTIONS a
WHERE c.NAME = :CATEGORY AND a.NAME = :ACTION
This however does not work. For some reason when I execute the query it complains that there's a conversion error for CATEGORY param.
This is the full code for this query operation:
procedure Test;
var
Query: TFDQuery;
begin
Query := TFDQuery.Create(nil);
try
Query.Connection := DBDataModule.dbMain;
Query.ResourceOptions.ParamCreate := False;
Query.SQL.BeginUpdate;
Query.SQL.Add('INSERT INTO RELATIONS (C_ID, M_ID, A_ID, A_INDEX)');
Query.SQL.Add('SELECT c.C_ID, 0, a.A_ID,:A_INDEX');
Query.SQL.Add('FROM CATEGORIES c, ACTIONS a');
Query.SQL.Add('WHERE c.NAME = :CATEGORY AND a.NAME = :ACTION');
Query.SQL.EndUpdate;
Query.Params.CreateParam(TFieldType.ftInteger, 'A_INDEX', ptInput);
Query.Params.CreateParam(TFieldType.ftFixedWideChar, 'CATEGORY', ptInput);
Query.Params.CreateParam(TFieldType.ftFixedWideChar, 'ACTION', ptInput);
Query.ParamByName('CATEGORY').Size := 255;
Query.ParamByName('ACTION').Size := 255;
Query.Prepare;
Query.ParamByName('A_INDEX').Value := 0;
Query.ParamByName('CATEGORY').Value := 'Foo';
Query.ParamByName('ACTION').Value := 'Foo';
Query.ExecSQL; // <-- Exception
finally
Query.Free;
end;
end;

I'm still learning about SQL, databases & FireDAC so I really don't understand why it will allow me to input a direct value into the select statement but a param is a no go.
How else could I dynamically insert a parameter into the A_INDEX column using the first query?
:A_INDEXis placed in the SELECT list. Try to change you query to for exampleINSERT INTO RELATIONS (C_ID, M_ID, A_ID, A_INDEX) SELECT c.C_ID, 0, a.A_ID, 0 FROM CATEGORIES c, ACTIONS a WHERE c_id=:A_INDEX AND c.NAME = :CATEGORY AND a.NAME = :ACTIONand I think it will run fine without any errors.A_INDEXcolumn dynamically, I can't have it be 0. Alsoc_id = :A_INDEXis wrong.c_IDis foreign key in table Relations and is tied to a primary keyc_IDin table Categories. My question is, why can I set a value for a column in the Select statement but I apparently can't put a parameter in there instead?:A_INDEXisn't processed because it is in the SELECT list. So I think you should try to make this statement where all parameters in the WHERE part and I think it will run without error. In this case the same set of parameters and in the same order will be used (:A_INDEX,:CATEGORY,:ACTION) so you will find the root of this issue.