Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL HELP - Conditional where clause based on a BIT variable - SQL Server

I need help writing a conditional where clause. here is my situation:

I have a bit value that determines what rows to return in a select statement. If the value is true, I need to return rows where the import_id column is not null, if false, then I want the rows where the import_id column is null.

My attempt at such a query (below) does not seem to work, what is the best way to accomplish this?


DECLARE @imported BIT

SELECT id, import_id, name FROM Foo WHERE
    (@imported = 1 AND import_id IS NOT NULL)
    AND (@imported = 0 AND import_is IS NULL)

Thanks.

like image 427
mmattax Avatar asked Mar 09 '09 16:03

mmattax


People also ask

Can we use variable in WHERE clause in SQL?

The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement. A common situation in which SQL variables come in handy is when you need to issue successive queries on multiple tables that are related by a common key value.

What can be the condition in WHERE clause in a SQL query?

The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records.

Does WHERE clause make query faster?

Adding indexed where clause will speedup the process, while adding non-indexed where clauses will force a full table scan and will certainly not enhance the performance.

How do you write an IF THEN statement in SQL?

Syntax. IF (a <= 20) THEN c:= c+1; END IF; If the Boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end if) will be executed.


2 Answers

Change the AND to OR

DECLARE @imported BIT

SELECT id, import_id, name FROM Foo WHERE
    (@imported = 1 AND import_id IS NOT NULL)
    OR (@imported = 0 AND import_is IS NULL)

Decomposing your original statement

you have essentially written

    @imported = 1 
    AND import_id IS NOT NULL
    AND @imported = 0 
    AND import_is IS NULL

wich is equivalent to

    @imported = 1 AND @imported = 0 
    AND import_id IS NOT NULL AND import_is IS NULL

what results in two pair of clauses that completely negate each other

like image 90
Lieven Keersmaekers Avatar answered Nov 07 '22 23:11

Lieven Keersmaekers


I think you meant

SELECT id, import_id, name FROM Foo WHERE
    (@imported = 1 AND import_id IS NOT NULL)
    OR (@imported = 0 AND import_is IS NULL)
    ^^^
like image 30
sfossen Avatar answered Nov 08 '22 00:11

sfossen