DateDiff Window in SQL Server

I have a table containing the last date / time when a particular function was launched. In my stored procedure, I want to return 1 if the current date / time is more than an hour from the last time it was started, and 0 if it is less. I currently 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 return only 1 if more than an hour has passed?

+3
source share
2 answers

Using:

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

Link:

How does rounding work with DateDiff?

The datepart Boundaries section of the documentation link contains this information.

+2
source

I think you want

IF DATEADD(hour, LastRunDateTime, 1) <= GETDATE() BEGIN
    RETURN 1;
END;
ELSE BEGIN
    RETURN 0;
END;

DateDiff , . , "" . :

PRINT DATEDIFF(HH, '2010-12-07T03:59:59', '2010-12-07T04:00:00');
PRINT DATEDIFF(HH, '2010-12-07T04:00:00', '2010-12-07T04:59:59');

:

1
0

, datetime . , , , .

+1

Source: https://habr.com/ru/post/1779044/


All Articles