2016-01-09 51 views
1

在假設我有4個變量:如何檢查時間範圍的時間範圍並獲得SQL中的冗餘時間?

@start = 5 AM 
@end = 8 AM 
@from = 10 PM 
@to = 6 AM 

@from@to被稱爲工作時間。上午時間稱爲@start@end

如何在「早晨時間」使用SQL檢查「工作時間」?如果發生,我需要獲得冗餘時間。

我是指從5AM到6AM等於1小時。下圖說明了更好的我的意思: enter image description here

+0

能eloborate你的意思是 「多餘的時間」 是什麼? –

回答

1

的僞代碼:

if ((@start < @to) and (@end > @from)) 
    return @to - @start 

當然你明白變量必須是DateTime型佔雙@from和@至超過兩跨越天。

編輯與完整的例子

declare @from datetime = '2015-12-31 22:00' 
declare @to datetime = '2016-01-01 06:00' 

declare @start datetime = '2016-01-01 05:00' 
declare @end datetime = '2016-01-01 08:00' 

if ((@start < @to) and (@end > @from)) 
    select datediff(hour, @start, @to) 

結果= 1

+0

你的回答是不正確的,我試試這個,我不能得到多餘的時間 –

+0

聲明開始日期時間= CONVERT(DATETIME,'05:00') 聲明結束日期時間= CONVERT(DATETIME,'08:00') 聲明從日期時間= CONVERT(DATETIME,'22:00 ') 聲明爲datetime = CONVERT(DATETIME,'06:00') 如果((啓動<至)和(端>從)) BEGIN SELECT 到 - 開始 END ELSE BEGIN \t select 1 END –

+0

您還必須聲明日期。很明顯,@from = 10PM是前一天。 – shadow