Add business days to date in SQL without loops

后端 未结 25 2866
无人共我
无人共我 2020-12-02 22:54

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 r

25条回答
  •  眼角桃花
    2020-12-02 23:35

    Thanks Damien for the code. There was a slight error in the calcs in that it added only 1 day for the sunday, and that when the number of business days crossed a weekend (but did not land in the weekend) the extra 2 days was not taken into account. Here is a modified version of Damiens code that works with the default datefirst at 7. Hope this helps.

    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  
    GO
    

提交回复
热议问题