Add business days to date in SQL without loops

后端 未结 25 2849
无人共我
无人共我 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:43

    Building off of the answer that was accepted for this question, the following user-defined function (UDF) should work in all cases--regardless of the setting for @@DateFirst.

    UPDATE: As comments below indicate, this function is designed for the FromDate to be a weekday. The behavior is undefined when a weekend day is passed in as the FromDate.

    ALTER FUNCTION [dbo].[BusinessDaysDateAdd] 
    (
       @FromDate datetime,
       @DaysToAdd int
    )
    RETURNS datetime
    AS
    BEGIN
       DECLARE @Result datetime
    
       SET @Result = DATEADD(day, (@DaysToAdd % 5) + CASE ((@@DATEFIRST + DATEPART(weekday, @FromDate) + (@DaysToAdd % 5)) % 7)
                                                     WHEN 0 THEN 2
                                                     WHEN 1 THEN 1
                                                     ELSE 0 END, DATEADD(week, (@DaysToAdd / 5), @FromDate))
    
       RETURN @Result
    END
    

提交回复
热议问题