5

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JJ.
  • 9,580
  • 37
  • 116
  • 189

2 Answers2

12

How about

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

SQLFiddle demo

juergen d
  • 201,996
  • 37
  • 293
  • 362
3

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
Community
  • 1
  • 1
StingyJack
  • 19,041
  • 10
  • 63
  • 122
  • Can you say `CAST(GETDATE() as TIME)`? –  Dec 16 '13 at 19:52
  • Dunno, have used the CAST/FLOOR/CAST for a while because it has always been the faster method. Your approach may be as good or better (its a heck of a lot shorter). Any idea if it is? – StingyJack Dec 16 '13 at 19:58
  • I couldn't get an actual compare of two SQL Server `TIME` objects to work unfortunately. Even MSDN recommends turning them into float. –  Dec 16 '13 at 20:58
  • I don't have a use the TIME data type as of yet. Everything still in DATETIME/DATETIME2 for me. – StingyJack Dec 16 '13 at 22:33