I have a table with the following schema:
| ID | BUNDLE_ID | IS_ADMIN |
I need to select data from the above table having an AND clause on the basis of certain criteria, i.e
IF @FLAG = 1
SELECT *
FROM TABLE A
WHERE A.IS_ADMIN = 1 AND BUNDLE_ID IN (3, 5)
ELSE
SELECT *
FROM TABLE A
WHERE A.IS_ADMIN = 1 AND BUNDLE_ID IN (1, 2)
Can I achieve this in a single query?
You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition.
Yes, a CASE statement is possible in the WHERE clause but in this case it doesn't seem like you need it.
Yes, an SQL query can contain a WHERE and HAVING clause.
The WHERE clause can be combined with AND , OR , and NOT operators. The AND and OR operators are used to filter records based on more than one condition: The AND operator displays a record if all the conditions separated by AND are TRUE.
General approach is to rewrite the query with a boolean expression that evaluates to what you need based on flag's value:
SELECT * FROM TABLE A WHERE A.IS_ADMIN = 1 AND ( -- Common part ...
(@Flag=1 AND BUNDLE_ID IN(3,5)) -- IF ...
OR
(@Flag<>1 AND BUNDLE_ID IN(1,2)) -- ELSE ...
)
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