IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'dbo.CF_Horas_Lab_Dif') 
                   and type = 'FN')
BEGIN
    DROP FUNCTION dbo.CF_Horas_Lab_Dif
END
GO

CREATE  FUNCTION CF_Horas_Lab_Dif(@ini DATETIME, @fin DATETIME,@hini TINYINT, @hfin TINYINT)
RETURNS INT
AS
BEGIN

DECLARE @aux  DATETIME
		,@dias INT 
		,@ret INT



IF DATEPART(hour,@ini) > @hfin
BEGIN
    SET @ini = @ini + 1
	SET @ini = CONVERT(DATE,@ini)
	SET @ini = DATEADD(hour,8,@ini)
END

SET @aux = @ini
SET @dias = 0
WHILE CONVERT(DATE,@aux) <= CONVERT(DATE,@fin)
BEGIN
	IF DATEPART(weekday,@aux) NOT IN (7,1)      --  Sab y Dom
	BEGIN
		SET @dias += 1
	END 
	SET @aux = DATEADD(dd,1,@aux)
END
SET  @ret =  ((@dias * 8) - (DATEPART(hour,@ini) - 9) - (17 - DATEPART(hour,@fin) )) 
IF @ret < 0 SET @ret = 0

RETURN @ret

END

/*
SELECT dbo.CF_Horas_Lab_Dif('20220629 18:00','20220630 18:15',8,17)

*/




