2013-02-12 36 views
6

Hi tất cả (! Bài viết đầu tiên của tôi trên Stack),cách sử dụng SQL WHERE CASE với NOT IN hoặc bằng cùng một lúc?

này hoạt động:

where 
    Tran_date between @FromDate and @ToDate 

and Range = @Range 

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

nhưng làm thế nào tôi có thể đạt được điều này ?:

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 

Trả lời

1

Tôi nghĩ bạn muốn:

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

Làm thế nào về điều này:

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) 
4
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 
Các vấn đề liên quan