Requête paramétrée, variable selon conditions
Bonjour,
Je coince sur un bête problème, j'ai besoin de mettre à jour 1 ou 2 champs sur une table, ce nombre étant fonction de la valeur de 2 variables...
Un peu de code pour expliquer:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| procedure TfrmMain.btnApplyPropertiesClick(Sender: TObject);
var
i1, iType, iWeight: Integer;
begin
if (not chkType.Checked) and (not chkWeight.Checked) then
Exit;
iType := -1;
iWeight := -1;
if chkType.Checked then
iType := cbbType.ItemIndex + 1;
if chkWeight.Checked then begin
case cbbWeight.ItemIndex of
0: iWeight := 20;
1: iWeight := 30;
2: iWeight := 40;
3: iWeight := 50;
4: iWeight := 60;
end;
end;
with qry do begin
SQL.Clear;
SQL.Add('UPDATE Boxes SET');
SQL.Add('Type = CASE WHEN :p0 = -1 THEN Type ELSE :p0 END,'); // Si iType = -1, on ne modifie pas le champ, sinon on lui donne la valeur iType
SQL.Add('Weight = CASE WHEN :p1 = -1 THEN Weight ELSE :p1 END'); // Si iWeight = -1, on ne modifie pas le champ, sinon on lui donne la valeur iWeight
SQL.Add('WHERE ID = :p2;');
StartTransaction;
Params[0].AsInteger := iType;
Params[1].AsInteger := iWeight;
for i1 := 0 to il.Count - 1 do begin // il de type TGpIntegerList
Params[2].AsInteger := il[i1];
ExecSQL;
end;
Commit;
end;
end; |
Hélas ça ne marche pas, j'ai essayé différentes modifications mais rien n'est mis à jour dans ma BDD avec ce code.
Du coup pour l'instant je passe par deux lots requêtes, ça marche mais ça me gêne de faire 2 requêtes pour ça:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| with qry do begin
if iType > -1 then begin
SQL.Clear;
SQL.Add('UPDATE Boxes SET Type = :p0 WHERE ID = :p1;');
StartTransaction;
Params[0].AsInteger := iType;
for i1 := 0 to il.Count - 1 do begin
Params[1].AsInteger := il[i1];
ExecSQL;
end;
Commit;
end;
if iWeight > -1 then begin
SQL.Clear;
SQL.Add('UPDATE Boxes SET Weight = :p0 WHERE ID = :p1;');
StartTransaction;
Params[0].AsInteger := iWeight;
for i1 := 0 to il.Count - 1 do begin
Params[1].AsInteger := il[i1];
ExecSQL;
end;
Commit;
end; |
Comment faire pour exécuter une seule requête, quel que soit le nombre de paramètres entrant en jeu, sans non plus passer par des tas de tests pour construire ma requête, genre "si param1 existe mais pas param2 alors SQL=...", "si param2 existe mais pas param1 alors SQL=...", "si param1 existe et param2 existe alors SQL=...", etc. ?
Info: j'utilise SQLite.