 
IF EXISTS (SELECT 1 FROM [dbo].[sysobjects] WHERE id = object_id(N'[dbo].[fn_AdjustDateForItemProcessTime]') AND xtype IN (N'FN', N'IF', N'TF')) 
	DROP FUNCTION [dbo].[fn_AdjustDateForItemProcessTime] 
GO 
 
CREATE FUNCTION [dbo].[fn_AdjustDateForItemProcessTime] 
(	 
	@entityId INT 
	, @date DATETIME 
	, @processingHours INT 
	, @closedDays UDT_ClosedDates READONLY 
) 
RETURNS DATETIME 
 
AS 
BEGIN 
 
	DECLARE 
		@isClosedDay BIT = 0 
		, @closedHours INT = 0 
		, @nextDate DATETIME = @date 
 
	-- Adjust the forecast date for item processing 
	SET @nextDate = DATEADD(HOUR, @processingHours, @date) 
 
	-- Check if the processing date is closed 
	SET @isClosedDay = CASE WHEN EXISTS (SELECT 1 FROM @closedDays WHERE ClosedDate = @nextDate) THEN 1 ELSE 0 END 
 
	WHILE (@isClosedDay = 1) -- Count the number of closed days. 
	BEGIN 
		SET @nextDate = DATEADD(DAY, 1, @nextDate) 
		SET @isClosedDay = CASE WHEN EXISTS (SELECT 1 FROM @closedDays WHERE ClosedDate = @nextDate) THEN 1 ELSE 0 END 
	END 
 
	SET @closedHours = DATEDIFF(HOUR, @date, @nextDate) 
 
	RETURN DATEADD(HOUR, @closedHours, @date) 
END 
 
GO 
