问题
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.
Code Below:
select FromTime, ToTime, datepart(HH, FromTime) as fromtimehours, datepart(HH, ToTime) as totimehours, DATEDIFF(HOUR, FromTime, ToTime) as totalhours from table
回答1:
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
来源:https://stackoverflow.com/questions/25042287/hours-difference-between-time-in-sql-server