【问题标题】:how use SQL WHERE CASE with NOT IN or equals at the same time?如何同时使用带有 NOT IN 或等于的 SQL WHERE CASE?
【发布时间】:2013-01-28 10:27:18
【问题描述】:

大家好(我在 Stack 上的第一篇文章!),

这行得通:

where
    Tran_date between @FromDate and @ToDate

and Range = @Range

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

但是我怎样才能做到这一点呢?:

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

【问题讨论】:

    标签: sql sql-server tsql case-when in-operator


    【解决方案1】:

    这个怎么样:

    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)
    

    【讨论】:

      【解决方案2】:

      我想你想要:

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

      【讨论】:

        【解决方案3】:
        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
        

        【讨论】:

          猜你喜欢
          • 2018-01-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-21
          • 2012-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多