此方法利用数字表创建查找表,查找您的@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