Warren
Warren

Reputation: 2024

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

Upvotes: 6

Views: 36999

Answers (3)

Kenneth Fisher
Kenneth Fisher

Reputation: 3812

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

Upvotes: 5

GilM
GilM

Reputation: 3771

I think you want:

AND NOT (@Range = 'RangeName' AND Store_ID IN (1234,5678))

Upvotes: 2

bobs
bobs

Reputation: 22204

How about this:

where Tran_date between @FromDate and @ToDate
    and Range = @Range

    and (@Range = 'RangeName' and Store_ID not in (1234, 5678)
        or @Range <> 'RangeName' and Store_ID = Store_ID)

Upvotes: 0

Related Questions