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.
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.
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.
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.
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.
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)
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
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)
^^^
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