if exists (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_EST_PROD_CPL_ULT_MOV_GLB_MOV_OP_ENTRADA]'))
begin
	DROP TRIGGER [dbo].[TRG_EST_PROD_CPL_ULT_MOV_GLB_MOV_OP_ENTRADA] 
	 
end

GO

CREATE TRIGGER [dbo].[TRG_EST_PROD_CPL_ULT_MOV_GLB_MOV_OP_ENTRADA] ON [dbo].[EST_NF_ENT_IT]   
FOR INSERT  
AS  
DECLARE @COD_NT_MOV    AS INT  
DECLARE @DT_MOV     AS DATETIME   

Begin  
   
	--Tratando notas complementar  
	IF EXISTS ( SELECT CD_EMP   
					FROM INSERTED   
					WHERE QT_IT = 0)  
	BEGIN  
		RETURN;  
	END   


  --Buscando dados para o processamento  
	SELECT       
		@COD_NT_MOV = EST_NF_ENT.CD_NT_MOV,   
		@DT_MOV		= EST_NF_ENT.DT_ENT 

	FROM           
		INSERTED i 
		INNER JOIN EST_NF_ENT ON   
		i.CD_EMP = EST_NF_ENT.CD_EMP AND   
		i.CD_FILIAL = EST_NF_ENT.CD_FILIAL AND   
		i.CD_NF = EST_NF_ENT.CD_NF 

	--deletando registro caso exista  
	DELETE  m  
	FROM    
		EST_PROD_CPL_ULT_MOV_GLB_MOV_OP m 
		INNER JOIN INSERTED i ON  
		m.CD_EMP	= i.CD_EMP AND  
		m.CD_FILIAL = i.CD_FILIAL AND  
		m.CD_MOV_OP = @COD_NT_MOV AND  
		m.CD_PROD	= i.CD_PROD  

	--Inserindo novo registro  
	INSERT INTO EST_PROD_CPL_ULT_MOV_GLB_MOV_OP  (   CD_EMP,   	CD_FILIAL,   	CD_PROD,   
													CD_MOV_OP,   	DT_MOV  	)  
	SELECT  
		CD_EMP,  
		CD_FILIAL,  
		CD_PROD,  
		@COD_NT_MOV,  
		@DT_MOV  
	FROM  
		INSERTED  
		
		
End  


