Skip to content
Advertisement

Compare two time strings in SQL

I have a string variable that denotes a time:

@time = '5:00 PM'

I need to check if the current time getdate() is after or before @time. How can I do this in SQL?

Advertisement

Answer

This should do it:

SQL 2008+

if datediff(ss,cast(@time as time),cast(GetDate() as time)) < 0
   print 'Future'
else
   print 'Past'

Earlier:

if DatePart(hh,GETDATE())*60+DATEPART(mm,getDate()) < DatePart(hh,@time)*60+DATEPART(mm,@time)   
   print 'Future' 
else   
   Print 'Past'
Advertisement