Where 子句 TSQL 中的 case 表达式
Posted
技术标签:
【中文标题】Where 子句 TSQL 中的 case 表达式【英文标题】:Case expression in Where Clause TSQL 【发布时间】:2020-01-03 19:34:02 【问题描述】:我正在尝试在 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 在 Effective 和 ExpirationDate 之间且 EntityId 为空”进行过滤
如果 IndividualRateSelectionOption 不是“ANV”,我想根据 EffectiveDate 和 ExpirationDate 之间的“isnull(@AnniversaryDate,@MemberEligibilityDate) 进行过滤 并且 EntityId 为空”
以上是我迄今为止尝试过的,但它抱怨语法。提前致谢。
【问题讨论】:
我不认为你真的需要一个案例陈述。 Just WHERE (x = 'ANV' AND date between x and y and id IS NULL) OR (x != 'ANV' AND date between x and y and id IS NULL) 虽然它可能对当前查询没有帮助,但this 答案显示了如何在on
子句中使用case
表达式。 where
子句的工作方式相同。
【参考方案1】:
当更简单的布尔逻辑起作用时,不要使用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
)
)
【讨论】:
以上是关于Where 子句 TSQL 中的 case 表达式的主要内容,如果未能解决你的问题,请参考以下文章
WHERE子句中的SQL Server CASE表达式以检查NULL值