I want to check if a boolean is true, then decide in the WHERE clause what condition to use.
Say the boolean variable is @checkbool:
SELECT *
FROM TableA A
WHERE
--if @checkbool is true, run this
A.Id = 123
--if @checkbool is false, run this
A.Id <> 123
Is there a way to negate a condition? Like in C++ you can do if !(condition).
If not, what is the best way to solve this problem?
Thank you!
Combining AND, OR and NOT in SQL By using SQL NOT, you can negate a specified condition, which means the value must be the opposite of the defined condition to be selected. The syntax for defining an SQL NOT condition is simple: Just like AND and OR, SQL NOT is usually used in the WHERE clause.
This SQL tutorial explains how to use the SQL NOT condition with syntax and examples. The SQL NOT condition (sometimes called the NOT Operator) is used to negate a condition in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement. This is the condition to negate.
FROM table_name WHERE condition; The WHERE clause appears immediately after the FROM clause. The WHERE clause contains one or more logical expressions that evaluate each row in the table. If a row that causes the condition evaluates to true, it will be included in the result set; otherwise, it will be excluded.
Description. The SQL NOT condition (sometimes called the NOT Operator) is used to negate a condition in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.
SQL's equivalent of !
in C is NOT
. However, in your case you want something else: you need to build a condition that decides between the two choices based on the value of @checkbool
, like this:
SELECT *
FROM TableA A
WHERE ( (@checkbool) AND (A.Id = 123))
OR ((NOT @checkbool) AND (A.Id <> 123))
Here is one solution:
IF @Checkbool = 1
SELECT * FROM Table A WHERE A.Id = 123
ELSE
SELECT * FROM Table A WHERE A.Id <> 123
Here is another using just the WHERE Clause:
SELECT *
FROM Table A
WHERE
(@Checkbool = 1 AND A.Id = 123)
OR
(@Checkbool = 0 AND A.Id <> 123)
Everything you put in the where clause needs to be in the form of an expression. Thus, the solution in this case is to write the condition in the form of an expression.
Hope this helps. :)
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