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

Warren picture Warren · Feb 13, 2013 · Viewed 33.7k times · Source

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

Answer

Kenneth Fisher picture Kenneth Fisher · Feb 13, 2013
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