Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add business days to date in SQL without loops

Tags:

date

sql

I currently have a function in my SQL database that adds a certain amount of business days to a date, e.g. if you enter a date that is a Thursday and add two days, it will return the date of the following Monday. I'm not bothered about any holidays, only weekends are excluded.

The problem is that this is currently done using a while loop, and it appears to be massively slowing down the stored procedure that uses it while generating a table. Does anyone know if there is any way to perform this calculation without while loops or cursors?

Just for information, this is the current function:

ALTER FUNCTION [dbo].[AddWorkDaysToDate] (    @fromDate       datetime, @daysToAdd      int ) RETURNS datetime AS BEGIN    DECLARE @toDate datetime DECLARE @daysAdded integer  -- add the days, ignoring weekends (i.e. add working days) set @daysAdded = 1 set @toDate = @fromDate  while @daysAdded <= @daysToAdd begin     -- add a day to the to date     set @toDate = DateAdd(day, 1, @toDate)     -- only move on a day if we've hit a week day     if (DatePart(dw, @toDate) != 1) and (DatePart(dw, @toDate) != 7)     begin         set @daysAdded = @daysAdded + 1     end end  RETURN @toDate  END 
like image 990
Matt King Avatar asked Mar 29 '11 11:03

Matt King


People also ask

How do I add only business days in SQL?

@@DateFirst values other than the default (7 aka U.S.). Specifying a custom list of non-weekend non-working days. Allowing list of non-weekend non-working days to work if passed-in date has a non-12 am time. Returning starting date-time if # work days increment is 0 even if starting date-time is on a non-working day.

How do I add 365 days in SQL?

To change a date and/or time by adding a specific number of a chosen unit of time, use SQL Server's DATEADD() function. This function works on date, time, or date and time data types.


1 Answers

This is better if anyone is looking for a TSQL solution. No loops, no tables, no case statements AND works with negatives. Can anyone beat that?

CREATE FUNCTION[dbo].[AddBusinessDays](@Date date,@n INT) RETURNS DATE AS  BEGIN DECLARE @d INT;SET @d=4-SIGN(@n)*(4-DATEPART(DW,@Date)); RETURN DATEADD(D,@n+((ABS(@n)+@d-2)/5)*2*SIGN(@n)-@d/7,@Date); END 
like image 80
ElmerMiller Avatar answered Oct 05 '22 16:10

ElmerMiller