本文介绍了sql server中时间之间的小时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用DATEDIFF(HOUR, FromTime, ToTime)获取两个日期之间的小时数,但是时间是00:00:00.而且我得到了错误和错误的小时数.

I am trying to get the hours between the two dates using DATEDIFF(HOUR, FromTime, ToTime) but when the time is 00:00:00. And the I got the negative and wrong hours.

以下代码:

select FromTime, ToTime, datepart(HH, FromTime) as fromtimehours,
datepart(HH, ToTime) as totimehours,
DATEDIFF(HOUR, FromTime, ToTime) as totalhours
from table

推荐答案

如果case语句为负值,然后正确计算,该例语句如何处理:

How about a case statement to catch if it is a negative value and then calculate properly:

CASE WHEN DATEDIFF(HOUR, FromTime, ToTime) < 0
THEN 24 - DATEPART(hour, FromTime) + DATEPART(hour, ToTime)
ELSE DATEDIFF(HOUR, FromTime, ToTime)
END AS TotalHours

这篇关于sql server中时间之间的小时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 06:30