sql server中的时间差小时

时间:2014-07-30 16:37:55

标签: sql sql-server datetime case

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

enter image description here

以下代码:

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

1 个答案:

答案 0 :(得分:2)

如果一个case语句是一个负值然后正确计算,它将如何捕获:

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