【无标题】SQL server 计算工作日(排除双休日)

计算工作日时间差

--计算工作时间相差小时数
CREATE FUNCTION dbo.fun_CalculateWorkdays
(
@startdate DATETIME,    -- 开始日期
@enddate DATETIME        -- 结束日期(结束日期须大于开始日期)
)
RETURNS INT
AS
BEGIN
--工作时间08:00--17:00
declare @shour int,   @intdays INT, @currentdate DATETIME
SET @intdays = 0
if datepart(hour,@startdate)<8 
begin 
--开始时间在8点前,算成8点
  set @startdate=CONVERT(nvarchar(10),@startdate,120)+' '+'08:00:00'
end
 if datepart(hour,@startdate)>17
begin
--开始时间在17点后,算成17点
set @startdate=CONVERT(nvarchar(10),@startdate,120)+' '+'17:00:00'
end 

if datepart(hour,@enddate)<8 
begin 
--结束时间在8点前,前一天算成17点
  set @enddate=CONVERT(nvarchar(10),@startdate-1,120)+' '+'17:00:00'
end
 if datepart(hour,@enddate)>17
begin
--结束时间在17点后,算成17点
set @startdate=CONVERT(nvarchar(10),@startdate,120)+' '+'17:00:00'
end 

SET @currentdate = @startdate
IF (DATEDIFF(d, @startdate, @enddate) < 0 OR @startdate IS NULL OR @enddate IS NULL OR @startdate = '' OR @enddate = '')
SET @intdays = 0

ELSE
BEGIN
WHILE (DATEDIFF(d, @currentdate, @enddate) >= 0)
BEGIN
IF (DATEPART(dw, @currentdate) = 7)
SET @currentdate = DATEADD(d, 1, @currentdate)
IF (DATEPART(dw, @currentdate) = 6)
SET @currentdate = DATEADD(d, 2, @currentdate)
IF (DATEPART(dw, @currentdate) <= 5)
BEGIN
SET @currentdate = DATEADD(d, 1, @currentdate)
SET @intdays = @intdays + 1
END
END
END
set @shour=0
if @intdays -1 =0
begin
  set @shour=datediff(hour,@startdate,@enddate)
end
if @intdays -1 =1
begin
  set @shour = datediff(hour,@startdate,convert(nvarchar(10),@startdate,120) + ' ' + '17:00:00') + datediff(hour, convert(nvarchar(10),@enddate,120) + ' ' +'08:00:00',@enddate)
end
if @intdays -1 >1
begin
  set @shour = (@intdays-2)*8 + datediff(hour,@startdate,convert(nvarchar(10),@startdate,120) + ' ' + '17:00:00') + datediff(hour, convert(nvarchar(10),@enddate,120) + ' ' +'08:00:00',@enddate)
end
RETURN (@shour)            
END

调用

select  dbo.fun_CalculateWorkdays('2022-04-08 10:00:00','2022-04-13 15:00:00')

你可能感兴趣的:(数据库开发,数据仓库)