I have a query to construct
Sometimes it will be
strSQL = ‘Select * from tableA’
sometimes it will be
strSQL = ‘Select * from tableA where FieldA > x’
sometimes it will be
strSQL = ‘Select * from tableA where FieldB < y’
and finally sometimes it’s
strSQL = ‘Select * from tableA where FieldA > x and FieldB < y’
So the ‘Where’ can be in front of either FieldA or FieldB.
I find that this can make for convoluted conditional logic to construct the query string.
My usual ‘trick’ is to put in a ‘Where’ clause that’s true for all records in the table so that fieldA and fieldB, if they are included, will always have an ‘And’ before them.
Something like
strSQL = ‘Select * from tableA where FieldC > 0’
if condition1 true
strSQL = strSQL + ‘ and FieldA > x’
end if
if condition2 true
strSQL = strSQL + ‘ and FieldA < B’
end if
Is there a better way to achieve this other than using more conditional logic in my code?
One trick is to use 1=1 as a condition…
Then proceed like you already have above. This will save the DBMS having to actually check any conditions on FieldC (which will always take processing time, even if FieldC is always >0), since 1=1 will be optimised out by the query parser.