此方法利用數字表創建查找表,查找您的@TimeIn
和@TimeOut
值之間的所有秒數。這將適用於多天的期間,儘管有一些嚴重的警告:
- 早餐,午餐和晚餐是在同一時間每天。
- 您的
@TimeIn
和@TimeOut
期間沒有那麼大,它溢出了包含seconds
的數字的int
值。
- 在這種情況下,你將需要或者只是使用
minutes
或找到一個不同的方法
- 你的返回值是小於24小時。
- 在這種情況下,不要將差異作爲
time
數據類型返回,並相應地處理它。
declare @TimeIn datetime = '2017-03-01 08:52:45.000'
,@TimeOut datetime = '2017-03-01 19:59:18.000'
,@BStart time = '06:30:39'
,@BEnd time = '10:00:39'
,@LStart time = '12:00:23'
,@LEnd time = '15:00:23'
,@DStart time = '19:00:39'
,@DEnd time = '21:00:39';
-- Create numbers table then use it to build a table os seconds between TimeIn and TimeOut
with n(n) as (select n from (values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) as n(n))
,s(s) as (select top (select datediff(s,@TimeIn,@TimeOut)+1) dateadd(s,row_number() over (order by (select 1))-1,@TimeIn) from n n1,n n2,n n3,n n4,n n5,n n6)
select cast(dateadd(s,count(1),0) as time) as s
from s
where s between @TimeIn and @TimeOut -- Return all seconds that aren't within Breakfast, Lunch or Dinner
and cast(s as time) not between @BStart and @BEnd
and cast(s as time) not between @LStart and @LEnd
and cast(s as time) not between @DStart and @DEnd
將返回:05:59:58.0000000
嗨,你可以有多個時間在和超時一天?或者它是固定的1次,每天1次出去 –
甚至更難 - 時間在一天,並在下一個時間(如在夜班)? –
那麼我已經整理出來的時間進出是單次進入。 – Kamran