简体   繁体   中英

Case expression in Where Clause TSQL

I'm trying to write a case expression in a where clause but I'm having trouble getting the syntax right for what I want to do. In the where clause I want to have the case statement check the column 'IndividualRateOption' and based on that column I want to add to the where clause.

--- Get generic rates
            select  case when RateType = 'PRE' then 1
                         when RateType = 'RID' then 2
                         when RateType = 'QUL' then 3 end,
                    BillingEntityId,
                    @GroupID,
                    RateID,
                    TierItemId,
                    RateUnitType,
                    RateUnitValue,
                    RateType,
                    RateTypeEntityID,
                    EffectiveDate,
                    ExpirationDate,
                    Usage,
                    AgeFrom,
                    AgeTo,
                    Gender,
                    PayBrokerCommissions
              from #BillingEntityRates
             where case IndividualRateSelectionOption when 'ANV' then @AnniversaryDate between EffectiveDate and ExpirationDate
                    OR isnull(@AnniversaryDate,@MemberEligibilityDate) between EffectiveDate and ExpirationDate
                    and EntityId is null

if IndividualRateSelectionOption is 'ANV' I want to filter based on "@anniversaryDate between Effective and ExpirationDate and EntityId is null"

If IndividualRateSelectionOption is not 'ANV' I want to filter based off "isnull(@AnniversaryDate,@MemberEligibilityDate) between EffectiveDate and ExpirationDate and EntityId is null"

Above is what I tried so far but the it's complaining about syntax. Thanks in Advance.

Don't use a case when simpler boolean logic works:

where (IndividualRateSelectionOption = 'ANV' and 
       @anniversaryDate between Effective and ExpirationDate and
       EntityId is null
      ) or
      (IndividualRateSelectionOption <> 'ANV' and 
       coalesce(@AnniversaryDate, @MemberEligibilityDate) between EffectiveDate and ExpirationDate and
       EntityId is null
      )

You can filter out the EntityId is null logic:

where EntityId is null and
      ( (IndividualRateSelectionOption = 'ANV' and 
         @anniversaryDate between Effective and ExpirationDate          
        ) or
        (IndividualRateSelectionOption <> 'ANV' and 
         coalesce(@AnniversaryDate, @MemberEligibilityDate) between EffectiveDate and ExpirationDate and
        )
      )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM