How to get Previous business day in a week with that of current Business Day using sql server

后端 未结 8 2171
情歌与酒
情歌与酒 2020-12-14 09:00

i have an ssis Package which runs on business days (mon-Fri). if i receive file on tuesday , background(DB), it takes previous business day date and does some transactions.

8条回答
  •  无人及你
    2020-12-14 09:44

    This function returns last working day and takes into account holidays and weekends. You will need to create a simple holiday table.

    -- =============================================
    -- Author:      Dale Kilian
    -- Create date: 2019-04-29
    -- Description: recursive function returns last work day for weekends and 
    -- holidays
    -- =============================================
    ALTER FUNCTION dbo.fnGetWorkWeekday
    (
        @theDate DATE
    )
    RETURNS DATE
    AS
    BEGIN
    
    DECLARE @importDate DATE = @theDate
    DECLARE @returnDate DATE
    --Holidays
    IF EXISTS(SELECT 1 FROM dbo.Holidays WHERE isDeleted = 0 AND @theDate = Holiday_Date)
    BEGIN
    SET @importDate = DATEADD(DAY,-1,@theDate);
    SET @importDate = (SELECT dbo.fnGetWorkWeekday(@importDate))
    END
    --Satruday
    IF(DATEPART(WEEKDAY,@theDate) = 7)
    BEGIN
        SET @importDate = DATEADD(DAY,-1,@theDate);
        SET @importDate = (SELECT dbo.fnGetWorkWeekday(@importDate))
    END
    --Sunday
    IF(DATEPART(WEEKDAY,@theDate) = 1)
    BEGIN
        SET @importDate = DATEADD(DAY,-2,@theDate);
        SET @importDate = (SELECT dbo.fnGetWorkWeekday(@importDate))
    END
    
    
    RETURN @importDate;
    END
    GO
    

提交回复
热议问题