Technical & Miscellaneous Ramblings
RSS icon Email icon Home icon
  • Next Business Day in SQL

    Posted on April 21st, 2009 Dhaneel No comments

    The other day I found myself needing to come up with a way to calculate the next business day including taking into account holidays. A recursive function turned out to be just the thing to use.

    Scripts
    To start with, you’ll need to create a table to hold the holidays: It can be any table which has just Holiday Date in it.

    CREATE TABLE [holiday] (
    [holidayDate] [smalldatetime] NOT NULL ,
    CONSTRAINT [PK_holidayDate] PRIMARY KEY CLUSTERED
    (
    [holidayDate]
    )
    )

    The function is

    SET QUOTED_IDENTIFIER ON
    GO
    SET ANSI_NULLS ON
    GO

    create function fnGetNextBusinessDay (@startDate smalldatetime,@numDays int)
    returns smalldatetime as

    Begin
    Declare @nextBusDay smalldatetime
    Declare @weekDay tinyInt

    set @nextBusDay = @startDate

    Declare @dayLoop int
    set @dayLoop = 0

    while @dayLoop < @numDays

    Begin
    set @nextBusDay = dateAdd(d,1,@nextBusDay) -- first get the raw next day

    SET @weekDay =((@@dateFirst+datePart(dw,@nextBusDay)-2) % 7) + 1

    -- always returns Mon=1 - can't use set datefirst in UDF
    -- % is the Modulo operator which gives the remainder
    -- of the dividend divided by the divisor (7)
    -- this allows you to create repeating
    -- sequences of numbers which go from 0 to 6
    -- the -2 and +1 adjust the sequence start point (Monday) and initial value (1)

    if @weekDay = 6 set @nextBusDay = @nextBusDay + 2 -- since day by day Saturday = jump to Monday

    -- Holidays - function calls itself to find the next business day

    select @nextBusDay = dbo.fnGetNextBusinessDay(@nextBusDay,1)
    where exists (select holidayDate from Holiday where holidayDate=@nextBusDay)

    -- next day
    set @dayLoop = @dayLoop + 1

    End

    return @nextBusDay

    End

    GO
    SET QUOTED_IDENTIFIER OFF
    GO
    SET ANSI_NULLS ON
    GO

    If date is something like 24/04/2009 which is Friday and if Monday is specified as holiday in Holiday table. It will written 28/04/2009

    Leave a reply