If exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_IsActiveInDateRange]') and xtype in (N'FN', N'IF', N'TF'))
	Drop function [dbo].[fn_IsActiveInDateRange]
GO

CREATE FUNCTION [dbo].[fn_IsActiveInDateRange] (  
 @EntityID bigint,  
 @IntroductionDate datetime,  
 @DiscontinueDate datetime,  
 @InUse int,  
 @LocalEntityTime datetime,
 @DiscontinueDateOverrideEnabled bit,
 @DiscontinueDateOverridden smallint
)    
RETURNS  Bit  
AS    
BEGIN  
  -- NOTE: If not inuse, return 1 if it has NOT been introduced    
  
 If @InUse = 1   
 BEGIN  
			 IF @DiscontinueDateOverrideEnabled = 1
			 BEGIN
				IF @DiscontinueDateOverridden = 0
				BEGIN
					-- Follow discontinue date.
					If(@IntroductionDate <= @LocalEntityTime) AND (@DiscontinueDate IS NULL OR @DiscontinueDate > @LocalEntityTime) RETURN 1
				END
				ELSE IF @DiscontinueDateOverridden = 1 
				BEGIN
					-- Force On
					RETURN 1
				END
				ELSE IF @DiscontinueDateOverridden = 2
				BEGIN
					-- Foce Off
					RETURN 0
				END
			  END
			  ELSE
			  BEGIN
				 -- Override disabled.
				 If (@IntroductionDate <= @LocalEntityTime	AND  (@DiscontinueDate IS NULL OR @DiscontinueDate > @LocalEntityTime)) RETURN 1  
			  END
 END  
 ELSE  
 Begin  
	  -- If not inuse, return 1 if it has NOT been introduced  
	  If (@IntroductionDate > @LocalEntityTime)   
	   Return 1  
 End  

 RETURN 0  
END   

