Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateDiff Rounding in SQL Server

I have a table that contains the last date/time a particular function was ran. In my stored procedure, I want to return 1 if the current date/time is more than an hour away from the last time it was ran and 0 if it was less. Currently I have this:

IF((SELECT TOP 1 DATEDIFF(HH,LastRunDateTime,GETDATE()) FROM myTable) >= 1)
BEGIN
    -- run statement to update LastRunDateTime
        return 1;
END
ELSE
    return 0;
END

How does rounding work with DateDiff?

Is there a better way to only return 1 if it has been more than an hour?

like image 696
Jason Avatar asked Apr 01 '26 02:04

Jason


1 Answers

Use:

SELECT CASE 
         WHEN DATEDIFF(hh, LastRunDateTime, GETDATE()) >= 1 THEN 1 
         ELSE 0 
       END

Reference:

  • DATEDIFF

How does rounding work with DateDiff?

The datepart Boundaries section in the documentation link provided lists such information.

like image 173
OMG Ponies Avatar answered Apr 02 '26 19:04

OMG Ponies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!