欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SQLServer 计算两个日期间的工作日(排除周六和周日,不排除节假日)

程序员文章站 2022-05-16 21:26:22
...
CREATE FUNCTION GetWorkDays
    (
      @dt_begin DATETIME , --计算的开始日期
      @dt_end DATETIME     --计算的结束日期
    )
RETURNS INT
AS 
    BEGIN

        DECLARE @workday INT ,
            @i INT ,
            @bz BIT ,
            @dt DATETIME

        IF @dt_begin > @dt_end 
            SELECT  @bz = 1 ,
                    @dt = @dt_begin ,
                    @dt_begin = @dt_end ,
                    @dt_end = @dt
        ELSE 
            SET @bz = 0
        SELECT  @i = DATEDIFF(Day, @dt_begin, @dt_end) + 1 ,
                @workday = @i / 7 * 5 ,
                @dt_begin = DATEADD(Day, @i / 7 * 7, @dt_begin)

        WHILE @dt_begin <= @dt_end 
            BEGIN
                SELECT  @workday = CASE WHEN ( @@DATEFIRST + DATEPART(Weekday, @dt_begin) - 1 )
                                             % 7 BETWEEN 1 AND 5 THEN @workday + 1
                                        ELSE @workday
                                   END ,
                        @dt_begin = @dt_begin + 1
            END
        RETURN(CASE WHEN @bz=1 THEN [email protected] ELSE @workday END)
    END
GO

--测试示例
SELECT  dbo.GetWorkDays('2019-08-1', '2019-08-31') AS '工作日'