SQL检查当前时间介于两个DATETIME列之间

时间:2017-12-20 09:07:41

标签: sql sql-server datetime

我需要检查当前时间是否在两个日期时间列值之间。

我只需要检查时间是否在范围之间,我不想查看日期。

我知道如何检查如下所示的日期范围之间的日期

SELECT
    *
FROM 
    Table1 T
WHERE 
    CAST(GETDATE() AS DATE) BETWEEN T.StartDate AND T.EndDate

我们已将开始日期和结束日期存储为替代..

StartDate - 1900-01-01 08:00:00.000
EndDate   - 1900-01-01 19:00:00.000

是否有与此相似的内容来检查日期范围内是否存在时间?

4 个答案:

答案 0 :(得分:4)

如果您只想查看时间

SELECT  *
FROM Table1 T
WHERE CAST(GETDATE() AS TIME) BETWEEN cast(T.StartDate as TIME) AND cast(T.EndDate as TIME)

答案 1 :(得分:1)

我想这样的东西

declare @d1 datetime ='20171220 10:00'
   , @d2 datetime = '20171220 12:00'
   , @t time ='11:00';
select 'Yes' where @t between cast(@d1 as time) and cast(@d2 as time);

答案 2 :(得分:1)

当我尝试下面的时候它起作用了

SELECT *
FROM Table1 T
WHERE CAST(GETDATE() AS TIME) BETWEEN CAST(T.StartDate AS TIME) AND CAST(T.EndDateAS TIME)

答案 3 :(得分:-1)

CONVERT()转到TIME,然后回到DATETIME并比较

WHERE CONVERT(DATETIME, CONVERT(TIME, GETDATE()))
      BETWEEN T.StartDate AND T.EndDate