2017-04-02 36 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); 

該處理的問題與你的表,這是一段時間包括午夜。

相關問題