1

I need to check whether the current time is between two datetime column values.

And I only need to check the time is between the range and I don't want to check the date.

I know how to check a date is exists between a daterange like below

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

We have stored start date and end date as folllows..

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

Is there something similar to this to check whether the time is exists in a date range?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
tarzanbappa
  • 4,930
  • 22
  • 75
  • 117

4 Answers4

7

if you only want to check time

SELECT  *
FROM Table1 T
WHERE CAST(GETDATE() AS TIME) BETWEEN cast(T.StartDate as TIME) AND cast(T.EndDate as TIME)
tarzanbappa
  • 4,930
  • 22
  • 75
  • 117
Ravi
  • 1,157
  • 1
  • 9
  • 19
1

Something like this I guess

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);
Serg
  • 22,285
  • 5
  • 21
  • 48
1

It worked when I tried like below

SELECT *
FROM Table1 T
WHERE CAST(GETDATE() AS TIME) BETWEEN CAST(T.StartDate AS TIME) AND CAST(T.EndDateAS TIME)
tarzanbappa
  • 4,930
  • 22
  • 75
  • 117
  • 1
    if can ensure the date is always `1900-01-01` then you don't need to CAST() or CONVERT() StartDate to `TIME`. This will avoid unnecessary scan and faster – Squirrel Dec 20 '17 at 09:31
-1

CONVERT() to TIME and then back to DATETIME and compare

WHERE CONVERT(DATETIME, CONVERT(TIME, GETDATE()))
      BETWEEN T.StartDate AND T.EndDate
Squirrel
  • 23,507
  • 4
  • 34
  • 32