Charles answered almost correctly.
It should be:
SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked = 0 OR col2 LIKE '%XYZ%')
This is the classic "pattern" in SQL for conditional predicates. If @checked = 0 , then it will return all rows corresponding to the rest of the predicate ( col1 = 'ABC' ). SQL Server doesn't even handle the second half of OR .
If @checked = 1 , then it will evaluate the second part of OR and return the rows matching col1 = 'ABC' AND col2 LIKE '%XYZ%'
If you have several conditional predicates, you can bind them together using this method (while the IF and CASE methods will quickly become unmanageable).
For instance:
SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked1 = 0 OR col2 LIKE '%XYZ%') AND (@checked2 = 0 OR col3 LIKE '%MNO%')
Do not use dynamic SQL, do not use IF or CASE.
source share