I had a requirement to create a query in SQL Server where the search condition would include/exclude a table based on user input.
Say I have two tables, TABLE_A
and TABLE_B
with columns KEYCOLUMN_A
and COLUMN_A
in TABLE_A
and columns FKCOLUMN_B
and COLUMN_B
in TABLE_B
.
And a query like:
SELECT TABLE_A.* FROM TABLE_A, TABLE_B WHERE TABLE_A.KEYCOLUMN_A = TABLE_B.FKCOLUMN_B
AND TABLE_A.COLUMN_A LIKE '%SEARCH%' AND TABLE_B.COLUMN_B LIKE '%SEARCH2%'
Now if the user does not input SEARCH2
, I don't need to search TABLE_B
. But this would mean an IF ELSE
clause. And as the number of "optional" tables in the query increases, the permutations and combinations would also increase and there will be many IF
and ELSE
statements.
Instead I decided to keep the statement as it is. So if SEARCH2
is empty, the query will effectively become:
SELECT * FROM TABLE_A, TABLE_B WHERE TABLE_A.KEYCOLUMN_A = TABLE_B.FKCOLUMN_B
AND TABLE_A.COLUMN_A LIKE '%SEARCH%' AND TABLE_B.COLUMN_B LIKE '% %'
Can the SQL optimizer recognize that LIKE %%
is as good as removing the condition itself?
Wrap an OR
around your "B" table, such as:
AND (len(searchString)=0 OR table_b.column_b LIKE "%searchString%" )
This way, if no value for the string, its length would be zero, and the first part of the OR
would be evaluated, always come back as true and return that portion of the equation as valid and ignore the other half using the LIKE
clause.
You could apply the same for as many linked tables as you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With