Count work days between two dates

前端 未结 24 2692
失恋的感觉
失恋的感觉 2020-11-22 01:05

How can I calculate the number of work days between two dates in SQL Server?

Monday to Friday and it must be T-SQL.

24条回答
  •  梦如初夏
    2020-11-22 01:51

    That's working for me, in my country on Saturday and Sunday are non-working days.

    For me is important the time of @StartDate and @EndDate.

    CREATE FUNCTION [dbo].[fnGetCountWorkingBusinessDays]
    (
        @StartDate as DATETIME,
        @EndDate as DATETIME
    )
    RETURNS INT
    AS
    BEGIN
        DECLARE @res int
    
    SET @StartDate = CASE 
        WHEN DATENAME(dw, @StartDate) = 'Saturday' THEN DATEADD(dd, 2, DATEDIFF(dd, 0, @StartDate))
        WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN DATEADD(dd, 1, DATEDIFF(dd, 0, @StartDate))
        ELSE @StartDate END
    
    SET @EndDate = CASE 
        WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN DATEADD(dd, 0, DATEDIFF(dd, 0, @EndDate))
        WHEN DATENAME(dw, @EndDate) = 'Sunday' THEN DATEADD(dd, -1, DATEDIFF(dd, 0, @EndDate))
        ELSE @EndDate END
    
    
    SET @res =
        (DATEDIFF(hour, @StartDate, @EndDate) / 24)
      - (DATEDIFF(wk, @StartDate, @EndDate) * 2)
    
    SET @res = CASE WHEN @res < 0 THEN 0 ELSE @res END
    
        RETURN @res
    END
    
    GO
    

提交回复
热议问题