在Sql中检查两个日期

时间:2016-03-26 11:06:24

标签: sql-server datetime

我有一个名为SHIFT的sql表,其列为:

No, Start, Duration(hours)
1,   7am,  7
2,   3pm,  7
3,  11pm,  7

如何使用sql查询知道哪个班次正在运行?

2 个答案:

答案 0 :(得分:2)

这是一个诀窍

;WITH cte
     AS (SELECT *,
                Cast(Cast(start AS DATETIME) AS TIME) AS start_time,
                Cast(Getdate() AS TIME)               AS curr_time
         FROM   (VALUES (1,'7am',7),
                        (2,'3pm',7),
                        (3,'11pm',7)) tc (No, Start, Duration))
SELECT TOP 1 No,
             Start,
             Duration
FROM   cte
WHERE  Datediff(second, start_time, curr_time) >= 0
ORDER  BY Datediff(second, start_time, curr_time) 

7am转换为datetime可为您提供1900-01-01 07:00:00.000

现在我们可以使用07:00:00.000 1900-01-01 07:00:00.000中的时间部分(datetime)与当前时间进行比较

答案 1 :(得分:0)

我建议添加计算列finish,以便按between运算符和< >

进行过滤
create table #test
(
  start time,
  lag   tinyint
)

insert into #test(start, lag)
values 
('7am', 7),
('8am', 3),
('10pm', 13),
('11am', 6)


alter table #test add finish as (dateadd(hh, lag, start))

/* all rows with computed column */
select * from #test

/* row with period current time falls in */
select *
from #test t
where cast(getdate() as time) between t.start and t.finish
order by t.start

drop table #test