2017-04-02 40 views
2

我有一个应用程序发送警报,如果温度超过限制,但我只想发送警报,如果它发生在一天的特定时间。我正在使用time(7)数据类型来存储这些时间。我需要的是足够的灵活性,跨越午夜,这样我就可以有时间如下:如何找出getDate()是否在2次(7)时间戳之间?

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

我怎么能计算出,如果CONVERT(时间(7),GETDATE())是任意的组合之间?

+0

有你的表日期字段? – McNets

+1

@zerkms向['Time(7)'](https://docs.microsoft.com/en-us/sql/t-sql/data-types/time-transact-sql)添加24小时是有问题的,因为它只能包含24小时以上的时间。更大的范围会使许多任务变得更容易。 – HABO

+0

@HABO很高兴知道,谢谢 – zerkms

回答

1

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

Declare @YourTable table (time_on time,time_off time) 
Insert Into @YourTable values 
('08:00:00','17:00:00'), 
('00:00:00','12:00:00'), 
('21:00:00','09:00:00'), 
('00:00:00','12:00:00'), -- Added for illustration 
('12:00:00','00:00:00') -- Added for illustration 


Declare @D datetime = convert(date,GetDate()) 

Select * 
From @YourTable 
Where GetDate() >= @D+convert(datetime,time_on) 
    and GetDate() <= @D+convert(datetime,time_off)+case when time_off<=time_on then 1 else 0 end 

返回截断电流GETDATE()至午夜

time_on    time_off 
12:00:00.0000000 00:00:00.0000000 

我的当前日期时间为2017年4月2日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 
1

你可以这样做:

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); 

该处理的问题与你的表,这是一段时间包括午夜。

相关问题