Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if the current time is between two times in SQL? [duplicate]

This isn't working:

IF EXISTS (( SELECT  1
            FROM    dbo.SalesOrder )
   AND (GETDATE() BETWEEN '07:00:00' AND '16:00:00'))
   BEGIN
         PRINT 'yes!'
   END

I want to do:

If something exists in the SalesOrder table AND the current time is between 7am and 4pm, then print 'YES'

I'm assuming I might have to do a conversion there but I'm unsure on how to do it properly.

Anyone care to give me a hand?

like image 565
JJ. Avatar asked Dec 16 '13 19:12

JJ.


2 Answers

How about

SELECT top 1 'yes'
FROM    dbo.SalesOrder
WHERE datepart(hour, GETDATE()) BETWEEN 7 and 16

SQLFiddle demo

like image 155
juergen d Avatar answered Nov 01 '22 21:11

juergen d


If you are trying to compare datetimes for the same day, you will need to remove the time component of GETDATE(), then add X hours. There are a few other conversions here.

IF EXISTS (( SELECT  1
            FROM    dbo.SalesOrder )
   AND (GETDATE() BETWEEN 
                      DATEADD(hh,7,(CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime))) AND DATEADD(hh,16,(CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime)))))
   BEGIN
         PRINT 'yes!'
   END
like image 33
StingyJack Avatar answered Nov 01 '22 19:11

StingyJack