Add business days to date in SQL without loops

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

    I don't have Sql Server at the moment to test but this is the idea:

    ALTER FUNCTION [dbo].[AddWorkDaysToDate]
    (   
    @fromDate       datetime,
    @daysToAdd      int
    )
    RETURNS datetime
    AS
    BEGIN   
    DECLARE @dw integer
    DECLARE @toDate datetime
    
    set datefirst 1
    set @toDate = dateadd(day, @daysToAdd, @fromDate)
    set @dw = datepart(dw, @toDate)
    
    if @dw > 5 set @toDate = dateadd(day, 8 - @dw, @toDate)
    
    RETURN @toDate
    
    END
    

提交回复
热议问题