Sql 如何确定getDate()是否在两(7)个时间戳之间?

Sql 如何确定getDate()是否在两(7)个时间戳之间?,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一个应用程序,可以在温度超过限制时发送警报,但我只想在一天中的特定时间发送警报。我使用时间(7)数据类型来存储这些时间。我需要它足够灵活,可以跨越午夜,这样我可以有以下时间: time_on  time_off 08:00:00  17:00:00 00:00:00  12:00:00 21:00:00  09:00:00 我如何确定CONVERT(time(7),getdate())是否介于这些组合之间?您可以将时间添加到datetime值中。在这里,我们通过Declare@D dat

我有一个应用程序,可以在温度超过限制时发送警报,但我只想在一天中的特定时间发送警报。我使用时间(7)数据类型来存储这些时间。我需要它足够灵活,可以跨越午夜,这样我可以有以下时间:

time_on   time_off
08:00:00  17:00:00
00:00:00  12:00:00
21:00:00  09:00:00

我如何确定CONVERT(time(7),getdate())是否介于这些组合之间?

您可以将时间添加到datetime值中。在这里,我们通过
Declare@D datetime=convert(date,GetDate())

我当前的日期时间是2017-04-02 18:33:53.803,这不符合任何原始标准,因此我添加了两条记录以供说明

或,如果您不想声明@D

Select *
 From  @YourTable
 Where GetDate() >= convert(datetime,convert(date,GetDate()))+convert(datetime,time_on)
   and GetDate() <= convert(datetime,convert(date,GetDate()))+convert(datetime,time_off)+case when time_off<=time_on then 1 else 0 end
选择*
从@YourTable
其中GetDate()>=convert(datetime,convert(date,GetDate()))+convert(datetime,time_on)
和GetDate()您可以执行以下操作:

select a.*
from alerttimes a
where (time_on <= time_off and cast(getdate() as time) >= time_on and cast(getdate() as time) < time_off) or
      (time_on > time_off and cast(getdate() as time) <= time_on and cast(getdate() as time) >= time_off);
选择一个*
从a时代开始
其中(time\u on=time\u on并转换(getdate()作为时间)time\u off and cast(getdate()作为时间)=time\u off);

这就解决了您的表的问题,即某些时段包括午夜。

您的表有日期字段吗?@zerkms将24小时添加到日期字段是有问题的,因为它只能包含少于24小时的时间。更大的范围会使许多任务变得更容易。@HABO很高兴知道,谢谢
Select *
 From  @YourTable
 Where GetDate() >= convert(datetime,convert(date,GetDate()))+convert(datetime,time_on)
   and GetDate() <= convert(datetime,convert(date,GetDate()))+convert(datetime,time_off)+case when time_off<=time_on then 1 else 0 end
select a.*
from alerttimes a
where (time_on <= time_off and cast(getdate() as time) >= time_on and cast(getdate() as time) < time_off) or
      (time_on > time_off and cast(getdate() as time) <= time_on and cast(getdate() as time) >= time_off);