Thursday, July 3, 2008

Function for calculating Working hours

Hi,
If you want to calculate simple working hours, i think this might help some,
Below function will return the working hour for the days between

CREATE FUNCTION [dbo].[WorkHours] ( @str_start DATETIME, @str_end DATETIME) RETURNS INT
AS
BEGIN
RETURN
(SELECT ((total_days / 7) * 5 + total_days % 7 -
CASE WHEN 6 BETWEEN start_weekday AND end_weekday
THEN 1 ELSE 0 END -
CASE WHEN 7 BETWEEN start_weekday AND end_weekday
THEN 1 ELSE 0 END) * 8 FROM (SELECT total_days, start_weekday,
start_weekday + total_days % 7 - 1
FROM (SELECT DATEDIFF(day, @start_date, @str_end) + 1,
DATEPART(WEEKDAY, @str_start + @@DATEFIRST - 1) ) AS T
(total_days, start_weekday) ) AS D
(total_days, start_weekday, end_weekday) );
END

Thought this might help someone who is struggling with the calculating the working hours, yes this may not serve the best result in customized situation given by clients but it happens some time that you just need to calculate something very straight.

Thanks
Parth

No comments: