Count work days between two dates

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

    Another approach to calculating working days is to use a WHILE loop which basically iterates through a date range and increment it by 1 whenever days are found to be within Monday – Friday. The complete script for calculating working days using the WHILE loop is shown below:

    CREATE FUNCTION [dbo].[fn_GetTotalWorkingDaysUsingLoop]
    (@DateFrom DATE,
    @DateTo   DATE
    )
    RETURNS INT
    AS
         BEGIN
             DECLARE @TotWorkingDays INT= 0;
             WHILE @DateFrom <= @DateTo
                 BEGIN
                     IF DATENAME(WEEKDAY, @DateFrom) IN('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
                         BEGIN
                             SET @TotWorkingDays = @TotWorkingDays + 1;
                     END;
                     SET @DateFrom = DATEADD(DAY, 1, @DateFrom);
                 END;
             RETURN @TotWorkingDays;
         END;
    GO
    

    Although the WHILE loop option is cleaner and uses less lines of code, it has the potential of being a performance bottleneck in your environment particularly when your date range spans across several years.

    You can see more methods on how to calculate work days and hours in this article: https://www.sqlshack.com/how-to-calculate-work-days-and-hours-in-sql-server/

提交回复
热议问题