Click here to Skip to main content
15,889,335 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have an sql Query to find out the overtime from two datetime. It works fine .But I need to get the time in hr:min:sec now it's coming in hr:min.Could anyone help me please.Any help will be really appreciated.

What I have tried:

case when CONVERT(varchar(6),DATEDIFF(second,010_05, 010_06)/3600) + ':' + RIGHT('0' + CONVERT(varchar(2), (DATEDIFF(second, 010_05, 010_06) % 3600) / 60), 2) + ':' + RIGHT('0' + CONVERT(varchar(2), DATEDIFF(second,010_05, 010_06) % 60), 2) >'8:30:00' then convert(char(5),cast(IN010_06 - dateadd(hour,8,DATEADD(MINUTE,30,010_05)) as time), 108) else '00:00' end as overtime
Posted
Updated 16-Jan-18 1:07am

1 solution

Don't do it like that! When you compare strings, it does a character by character comparison, and the result of the whole comparison is based on teh first different characters it finds.
So if someone does 10 hours of overtime, you will end up comparing "10:00:00" with "8:30:00" and the result will be wrong - as '1' comes before '8' in the character set, "10:00:00" is less than "8:30:00". And that will annoy your workers immensely...

Instead of wasting your time converting things to styrings and faffing with them, get the difference in total seconds as an integer, and compare that directly against 8 hours, 30 minutes as seconds: > 30600 (8 * 60 * 60 + 30 *60 + 0).
The SQL looks tidier and more readable, and it's less prone to errors.

You can then use "% 60" and "/ 60" to break down the result into hours, minutes, and seconds for return (or better return it as a number of seconds overtime and let the presentation software sort out a display format).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900