Count work days between two dates

前端 未结 24 3006
失恋的感觉
失恋的感觉 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:50

    Create function like:

    CREATE FUNCTION dbo.fn_WorkDays(@StartDate DATETIME, @EndDate DATETIME= NULL )
    RETURNS INT 
    AS
    BEGIN
           DECLARE @Days int
           SET @Days = 0
    
           IF @EndDate = NULL
                  SET @EndDate = EOMONTH(@StartDate) --last date of the month
    
           WHILE DATEDIFF(dd,@StartDate,@EndDate) >= 0
           BEGIN
                  IF DATENAME(dw, @StartDate) <> 'Saturday' 
                         and DATENAME(dw, @StartDate) <> 'Sunday' 
                         and Not ((Day(@StartDate) = 1 And Month(@StartDate) = 1)) --New Year's Day.
                         and Not ((Day(@StartDate) = 4 And Month(@StartDate) = 7)) --Independence Day.
                  BEGIN
                         SET @Days = @Days + 1
                  END
    
                  SET @StartDate = DATEADD(dd,1,@StartDate)
           END
    
           RETURN  @Days
    END
    

    You can call the function like:

    select dbo.fn_WorkDays('1/1/2016', '9/25/2016')
    

    Or like:

    select dbo.fn_WorkDays(StartDate, EndDate) 
    from table1
    

提交回复
热议问题