sql - 在带有 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
解决方案
只需使用常规逻辑:
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
,因为它会妨碍优化器。. . 而且可能更难遵循。通常,可以使用基本布尔逻辑来表示相同的逻辑。
推荐阅读
- javascript - 在 reactjs 状态下通过数组表示法更新嵌套对象值
- html - 当我的输入被禁用时,如何从日期输入字段中删除 dd-mm-yyy
- laravel - 如何在 Vue JS 中显示图像
- python - 预测多线程时出现 Keras 错误
- oracle - 案例和提取功能的问题
- php - 为什么当我使用 foreach 时我的代码只向 DB 插入一个
- identityserver4 - 使用隐式流访问 API 资源
- angular - 如何删除使用 nativescript-camera 创建的 NativeScript ImageAsset?
- python - map() 作为类成员与 map() 作为独立函数?
- java - 我想为游戏桌使用 getter 和 setter