Count work days between two dates

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

    My version of the accepted answer as a function using DATEPART, so I don't have to do a string comparison on the line with

    DATENAME(dw, @StartDate) = 'Sunday'
    

    Anyway, here's my business datediff function

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE FUNCTION BDATEDIFF
    (
        @startdate as DATETIME,
        @enddate as DATETIME
    )
    RETURNS INT
    AS
    BEGIN
        DECLARE @res int
    
    SET @res = (DATEDIFF(dd, @startdate, @enddate) + 1)
        -(DATEDIFF(wk, @startdate, @enddate) * 2)
        -(CASE WHEN DATEPART(dw, @startdate) = 1 THEN 1 ELSE 0 END)
        -(CASE WHEN DATEPART(dw, @enddate) = 7 THEN 1 ELSE 0 END)
    
        RETURN @res
    END
    GO
    

提交回复
热议问题