计算两个日期相差的工作小时数,过滤了周末双休小时数

CREATE FUNCTION [dbo].[gdcfn_GetWorkHour](
@dt_begin datetime,  --计算的开始日期
@dt_end  datetime    --计算的结束日期
)RETURNS int
AS
BEGIN    
    declare @hourNum int
    if @dt_begin is null or @dt_begin<@dt_end or @dt_end is null begin set @hourNum=null end
    
    set @hourNum=0
    declare @tempDate datetime,@tempEndDate datetime
    set @tempDate=@dt_begin --dateadd(dd,1,@dt_begin)
    while @tempDate<@dt_end
    begin
        set @tempEndDate=convert(varchar(10),dateadd(dd,1,@tempDate),120)+' 00:00:00'
        if datepart(dw,@tempDate) in(1,7) begin
            if @tempEndDate>@dt_end begin set @tempEndDate=@dt_end end
            set @hourNum=datediff(HH,@tempDate,@tempEndDate)
        end
        set @tempDate=@tempEndDate
    end
    return datediff(HH,@dt_begin,@dt_end)-@hourNum
end

原文地址:https://www.cnblogs.com/huaan011/p/3446183.html