CREATE function dbo.GetBusinessHours
/*******************************************************/
/* Written by: J.D. Gonzalez to include busines hours */
/* Purpose: Provide the number of business hours */
/* between two dates. Business days */
/* are classified as Monday - Friday */
/*******************************************************/
(
@StartDate datetime,
@EndDate datetime
)
returns decimal(9,2)
as
begin
/*Variable declaration */
declare @HoursBetween decimal(9,2) /* calculated number of hours between startdate and enddate */
declare @minutesBetween decimal(9,2) /* number of minutes between startdate and enddate */
declare @BusinessHours decimal(9,2) /* calculated number of business hours */
declare @Cnt int /* temp counter used to add the hour to the startdate */
declare @EvalDate datetime /* temp date used in evaluation */
declare @strip as decimal(9,2) /* strips out decimal from @hours between */
select @HoursBetween = 0 /* set @hoursbetween to zero */
select @BusinessHours = 0 /* set @businessHours to zero */
select @Cnt=0 /* set the counter to zero */
select @minutesBetween = datediff(mi,@StartDate,@endDate) /* determine number of minutes between start and end dates */
select @HoursBetween = @minutesBetween/60 /* change to hours */
select @strip = right(@hoursBetween,3) /* strip out decimal from @hoursbetween */
/* Program logic */
while @Cnt < @HoursBetween /*cycle through the entire interval of hours */
begin
select @EvalDate = dateadd(hh,@cnt,@StartDate) /* getdate to evaluate */
/* add one hour if the does not fall on a Saturday or Sunday */
if (((datepart(dw,@EvalDate) <> 1) and (datepart(dw,@EvalDate) <> 7)) and
(datepart(hh,@EvalDate) not in (0,1,2,3,4,5,6,7,12,17,18,19,20,21,22,23)))
/*Indicates what times not to count -- 00:00am to 7:59am, noon, 05:00pm to 11:59pm*/
BEGIN
select @BusinessHours = @BusinessHours + 1
END
select @Cnt = @Cnt + 1 /* Increment counter */
end
select @BusinessHours = @BusinessHours + @strip /* add decimal portion back to @hours */
return @BusinessHours /* return value back to calling statement */
end