[英]Case expression in Where Clause TSQL
我正在嘗試在 where 子句中編寫一個 case 表達式,但是我在為我想要做的事情找到正確的語法時遇到了麻煩。 在 where 子句中,我想讓 case 語句檢查列“IndividualRateOption”,並基於該列我想添加到 where 子句中。
--- 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
如果IndividualRateSelectionOption 是'ANV',我想根據“有效和到期日期之間的@anniversaryDate 和EntityId 為空”進行過濾
如果IndividualRateSelectionOption 不是'ANV',我想根據EffectiveDate 和ExpirationDate 之間的“isnull(@AnniversaryDate,@MemberEligibilityDate) 和EntityId 為空”進行過濾
以上是我迄今為止嘗試過的,但它抱怨語法。 提前致謝。
不要使用case
時,簡單的布爾邏輯的工作原理:
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
)
您可以過濾掉EntityId is null
邏輯:
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
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.