Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how use SQL WHERE CASE with NOT IN or equals at the same time?

Hi all (my first post on the Stack!),

This works:

where
    Tran_date between @FromDate and @ToDate

and Range = @Range

and Store_ID =
    case when @Range = 'RangeName' then
        1234
    else
        Store_ID
    end

but how can I achieve this?:

where
    Tran_date between @FromDate and @ToDate

and Range = @Range

and Store_ID 
    case when @Range = 'RangeName' then
        not in (1234, 5678)
    else
        Store_ID
    end
like image 738
Warren Avatar asked Feb 12 '13 23:02

Warren


People also ask

Can we use two conditions in case statement in SQL?

Multiple conditions in CASE statement You can evaluate multiple conditions in the CASE statement.

Can you have multiple WHERE statements in SQL?

You can use the OR condition in the WHERE clause to test multiple conditions where the record is returned if any one of the conditions are met. This example uses the WHERE clause to define multiple conditions, but instead of using the AND condition, it uses the OR condition.

Can we use in and not in together in SQL?

IN and NOT IN clause on the same column is legit and logical. It's just like doing Set Minus (Set A - Set B) . thus the result.

Can we put case in WHERE condition in SQL?

CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.


2 Answers

where
    Tran_date between @FromDate and @ToDate

and Range = @Range

and Store_ID 
    case when @Range = 'RangeName' AND Store_Id in (1234, 5678)
        9999 -- Assumes 9999 is a non possible value.  
             -- If it is possible then pick one that isn't.
    else
        Store_ID
    end
like image 118
Kenneth Fisher Avatar answered Oct 08 '22 07:10

Kenneth Fisher


I think you want:

AND NOT (@Range = 'RangeName' AND Store_ID IN (1234,5678))
like image 25
GilM Avatar answered Oct 08 '22 07:10

GilM