IF NOT OBJECT_ID('TRG_EST_SNGPC_ENTRADA_UPDATE_DELETE') IS NULL
	BEGIN 
		DROP TRIGGER TRG_EST_SNGPC_ENTRADA_UPDATE_DELETE 
	END 
GO

CREATE TRIGGER TRG_EST_SNGPC_ENTRADA_UPDATE_DELETE ON EST_SNGPC_ENTRADA FOR DELETE, UPDATE
AS 
IF EXISTS ( SELECT TOP 1 A.CD_LOTE
			FROM   
				EST_SNGPC_SAIDA A 
				INNER JOIN EST_SNGPC_ENT_SAI S ON 
				S.CD_SAI_SNGPC 	= A.CD_SAI_SNGPC AND 
				S.CD_FILIAL 	= A.CD_FILIAL  
				INNER JOIN DELETED D ON 
				A.CD_LOTE 	= D.CD_LOTE AND 
				A.DT_MOV 	>= D.DT_MOV AND 
				A.CD_FILIAL = D.CD_FILIAL AND 
				S.CD_PROD 	= D.CD_PROD) 
		BEGIN
			RAISERROR ('Lote com lancamento de saidas ja efetivado. Alteracao cancelada.',16, 1);
			ROLLBACK TRANSACTION;
			RETURN;
		END	