IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[F_DT_ULT_PROC_EST_FECHA_PROC_MOV]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[F_DT_ULT_PROC_EST_FECHA_PROC_MOV]
GO
--select dbo.F_DT_ULT_PROC_EST_FECHA_PROC_MOV(1,7,1,'2012-10-16')
CREATE  FUNCTION [dbo].[F_DT_ULT_PROC_EST_FECHA_PROC_MOV](	@CD_EMP 		INT,
																@CD_FILIAL 		INT,
																@CD_PROD 		INT,
																@DT_PROC 		DATETIME)
RETURNS DATETIME WITH ENCRYPTION AS  
BEGIN

DECLARE @DT_PROC_MIN DATE 

SET @DT_PROC_MIN = (SELECT
						MAX(DT_PROC) DT_PROC
					FROM 
						EST_FECHA_PROC_MOV with (nolock)
					WHERE 
						CD_EMP =@CD_EMP 
						AND CD_FILIAL	=@CD_FILIAL
						AND CD_PROD		=@CD_PROD
						AND DT_PROC		< @DT_PROC  )


IF @DT_PROC_MIN IS NULL
	begin
		SET @DT_PROC_MIN = dateadd(day,-180 ,GETDATE() )
		SET @DT_PROC_MIN = dateadd(day, (datepart(day,@DT_PROC_MIN)-1)*-1, @DT_PROC_MIN)
	end

RETURN @DT_PROC_MIN
END


