SQL如何实现跨天时段筛选,获取表中存储的对应待执行查询语句
跨天时段SQL筛选解决方案
改造后的查询语句如下:
select query from tblQuery where (starthour <= endhour and datepart(hour, getdate()) between starthour and endhour) OR (starthour > endhour and (datepart(hour, getdate()) >= starthour OR datepart(hour, getdate()) <= endhour))
逻辑说明
- 同天时段(开始小时≤结束小时):直接沿用原有
between匹配逻辑即可正常生效 - 跨天时段(开始小时>结束小时):只要当前小时大于等于开始小时(匹配当日执行区间),或是小于等于结束小时(匹配次日凌晨执行区间),就符合执行条件。比如配置
starthour=13、endhour=2时,1323点、02点都会被判定为符合时段要求
如果使用其他数据库,只需调整取当前小时的语法即可:
- MySQL替换为
hour(now()) - PostgreSQL替换为
extract(hour from now())
内容的提问来源于stack exchange,提问作者Jen K
相关产品推荐
相关产品推荐

