这就是我一直在寻找的,这是其他人需要的代码:
参数是:
@D1 (StartDate)
@D2 (EndDate)
@T1 (Business Hours - Start)
@T2 (Business Hours - End)
该函数返回一个带有小时数的浮点数。
CREATE FUNCTION [dbo].[WorkHoursDiff] (@D1 as datetime,@D2 as datetime,@T1 as int,@T2 as int)
RETURNS float AS
BEGIN
if @D1>@D2 return 0
declare @whd as float
declare @H1 as float
declare @H2 as float
if not (datepart(yyyy,@D1 )=datepart(yyyy,@D2) and datepart(mm,@D1)=datepart(mm,@D2) and datepart(dd,@D1)=datepart(dd,@D2))
begin
declare @DD as datetime
SET @whd=0
if datepart(dw,@D1)<>1 and datepart(dw,@D1)<>7
if dbo.GetDateHour(@D1)<@T1 SET @whd = @T2-@T1
else if dbo.GetDateHour(@D1)>@T2 SET @whd = 0
else if dbo.GetDateHour(@D1)>=@T1 and dbo.GetDateHour(@D1)<=@T2 SET @whd = @T2-dbo.GetDateHour(@D1)
SET @DD=@D1 + 1
while not (datepart(yyyy,@DD)=datepart(yyyy,@D2) and datepart(mm,@DD)=datepart(mm,@D2) and datepart(dd,@DD)=datepart(dd,@D2))
begin
if not(datepart(dw,@DD)=1 or datepart(dw,@DD)=7)
SET @whd=@whd + (@T2-@T1)
SET @DD=@DD + 1
end
if datepart(dw,@D2)<>1 and datepart(dw,@D2)<>7
if dbo.GetDateHour(@D2)<@T1 SET @whd = @whd
else if dbo.GetDateHour(@D2)>@T2 SET @whd = @whd + @T2 - @T1
else if dbo.GetDateHour(@D2)>=@T1 and dbo.GetDateHour(@D2)<=@T2 SET @whd = @whd +dbo.GetDateHour(@D2)-@T1
end
else
begin
if dbo.GetDateHour(@D1)<@T1 SET @H1=@T1
else if dbo.GetDateHour(@D1)>@T2 SET @H1=@T2
else SET @H1=dbo.GetDateHour(@D1)
if dbo.GetDateHour(@D2)<@T1 SET @H2=@T1
else if dbo.GetDateHour(@D2)>@T2 SET @H2=@T2
else SET @H2=dbo.GetDateHour(@D2)
if datepart(dw,@D1)=1 or datepart(dw,@D1)=7 SET @whd=0
else SET @whd=@H2-@H1
end
return @whd
END