简体   繁体   English

SQL Server中的DateDiff舍入

[英]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. 在我的存储过程中,如果当前日期/时间距离上次运行时间超过一小时,则返回1,如果距离较小,则返回0。 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? 如何使用DateDiff进行舍入?

Is there a better way to only return 1 if it has been more than an hour? 如果超过一小时,是否有更好的方法只返回1?

Use: 使用:

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

Reference: 参考:

How does rounding work with DateDiff? 如何使用DateDiff进行舍入?

The datepart Boundaries section in the documentation link provided lists such information. 提供的文档链接中的datepart Boundaries部分列出了这些信息。

I think you want 我想你想要的

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

DateDiff is a little more subtle than just subtracting two datetimes. DateDiff比仅减去两个日期时间更微妙。 It actually tells you how many "boundaries" are crossed between the two. 它实际上告诉你两者之间有多少“边界”。 For example: 例如:

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');

prints the following: 打印以下内容:

1
0

which is confusing, because the second pair of datetimes are farther apart. 这令人困惑,因为第二对日期时间相距甚远。 This functionality is great when you need it, but counterintuitive when you don't. 当你需要它时,这个功能很棒,但是当你不需要时,它就是违反直觉的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM