首页 > 解决方案 > 在带有 BETWEEN 的 WHERE 子句中使用 CASE

问题描述

我正在尝试使用 case 语句编写 where 子句,该语句将查看 @TimeType,然后仅返回这些时间范围之间的行。所以基本上我有3次(早上,下午和晚上)。我在使用 between 时遇到语法错误。start_time 字段是 sql 时间数据类型。这是我到目前为止所拥有的:

declare @TimeType int

select * from events
where
start_time = case 
when @TimeType = 0 then start_time between '00:00:00' and '11:59:00' 
when @TimeType = 1 then start_time between '12:00:00' and '16:59:00' 
when @TimeType = 2 then start_time between '17:00:00' and '23:59:00' 
end

标签: sqlsql-servertsql

解决方案


只需使用常规逻辑:

select e.* 
from events e
where (@TimeType = 0 and start_time between '00:00:00' and '11:59:00') or
      (@TimeType = 1 then start_time between '12:00:00' and '16:59:00') or 
      (@TimeType = 2 then start_time between '17:00:00' and '23:59:00');

一般来说,不鼓励case在子句中使用表达式where,因为它会妨碍优化器。. . 而且可能更难遵循。通常,可以使用基本布尔逻辑来表示相同的逻辑。


推荐阅读