Add business days to date in SQL without loops

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

    This SQL function works similar to Excel WORKDAY function. Hope it can help you.

    CREATE FUNCTION [dbo].[BusDaysDateAdd] 
    (
       @FromDate date,
       @DaysToAdd int
    )
    RETURNS date
    AS
    BEGIN
       DECLARE @Result date
       DECLARE @TempDate date
       DECLARE @Remainder int
       DECLARE @datePartValue int
    
       SET @TempDate = (DATEADD(week, (@DaysToAdd / 5), @FromDate))
       SET @Remainder = (@DaysToAdd % 5)
       SET @datePartValue = DATEPART(weekday, @TempDate)
       SET @Result = DATEADD(day,@Remainder + CASE WHEN @Remainder > 0 AND @datePartValue = 7 THEN 1
                                                    WHEN @Remainder >= 1 AND @datePartValue = 6 THEN 2
                                                    WHEN @Remainder >= 2 AND @datePartValue = 5 THEN 2
                                                    WHEN @Remainder >= 3 AND @datePartValue = 4 THEN 2
                                                    WHEN @Remainder >= 4 AND @datePartValue = 3 THEN 2
                                                    WHEN @Remainder >= 5 AND @datePartValue = 2 THEN 2
                                                    ELSE 0 END, @TempDate)
       RETURN @Result
    END
    GO
    

    Reference

提交回复
热议问题