SQL Server: Calculate Business Days

I needed to add/subtract some days based on a date specified.And exclude Saturday's and Sunday's as well. Meaning calculate business days.
CREATE FUNCTION [dbo].[fn_AddBusinessDays]
(
@StartDate datetime,
@BusinessDays int
)
RETURNS datetime
AS
BEGIN
DECLARE @EndDate datetime

SET @EndDate = DATEADD(day, @BusinessDays%5 +
CASE
WHEN DATEPART(weekday,@StartDate) + @BusinessDays%5 > 6 THEN 2
ELSE 0
END,
DATEADD(week,@BusinessDays/5,@StartDate))

RETURN @EndDate
END

If you need to add 2 days use the function as shown below
select '2014-01-24',dbo.fn_AddBusinessDays('2014-01-24',2)

If you need to subtract 2 days you can use it as shown below. Just make it -2.
select '2014-01-24',dbo.fn_AddBusinessDays('2014-01-24',-2)

No comments:

Post a Comment