When mounting SELECTS
at runtime we always have the problem of knowing what might be coming or not depending on the choices made by the user.
When assembling the WHERE
clause we are faced with the question of adding AND
or not before each condition.
If it is the first condition then it will not have the AND
, however if it is the second or greater than this we add at the beginning of the condition AND
.
To not be held hostage to this condition, having to analyze it at all times I add an innocuous clause and then I can add AND
to all the others.
In this way my WHERE
fault clause is WHERE 0 = 0
, so I can add AND
to all other conditions.
At run time my WHERE
clause will look like this: WHERE 0 = 0 AND condicao1 = 'cond1' AND condicao2 = 'cond2' AND condicao3 = 3
or just like this: WHERE 0 = 0
and it will work without problems.
When we mount a UPDATE
at runtime we have the same problem, but the question now is the comma or the total lack of parameters.
We start with "UPDATE tabelax SET"
and we're adding columns as the program finds those tags.
At first we add "campo1 = 'campo1'" + ","
, in the second "campo2 = 'campo2' + ","
. Note that we could not add the comma if field2 were the last field filled because otherwise our final command would be wrong. UPDATE tabelax SET campo1 = 'campo1', campo2 = 'campo2', WHERE condicao
is wrong. That is, you have to ask if it is the last one or not, or add in all and at the end of the loop check if the last character is a comma and remove it before adding the WHERE
clause.
Anyway, the question: does not have a way, like the case of WHERE
,
is it easier, smarter or clever to solve this?