IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_EST_PROD_CPL_EDELIVERY_SINC]'))
DROP TRIGGER TRG_EST_PROD_CPL_EDELIVERY_SINC
GO

CREATE TRIGGER TRG_EST_PROD_CPL_EDELIVERY_SINC ON EST_PROD_CPL AFTER UPDATE, INSERT AS  
begin  

	SELECT I.CD_EMP, I.CD_FILIAL, I.CD_PROD
	INTO #INSERTED
	FROM INSERTED I
	LEFT JOIN DELETED D ON D.CD_PROD = I.CD_PROD
						  AND I.CD_FILIAL = D.CD_FILIAL
						  AND D.CD_EMP = I.CD_EMP
	WHERE I.QT_EST <> ISNULL(D.QT_EST,0)
	AND I.QT_EST IS NOT NULL

	IF EXISTS (SELECT 1 FROM #INSERTED)
	BEGIN

			UPDATE E
			SET DT_ULT_ALT = GETDATE()
			FROM EDELIVERY_EST_PROD_SINC E 
			INNER JOIN #INSERTED I ON I.CD_PROD = E.CD_PROD AND I.CD_FILIAL = E.CD_FILIAL
		
			INSERT INTO EDELIVERY_EST_PROD_SINC
			SELECT CD_EMP, CD_FILIAL, CD_PROD, GETDATE()
			FROM #INSERTED I
			WHERE NOT EXISTS (SELECT 1 
				   FROM EDELIVERY_EST_PROD_SINC (NOLOCK) E
				   WHERE E.CD_PROD = I.CD_PROD
				   AND I.CD_FILIAL = E.CD_FILIAL)
	END
END

GO

ALTER TABLE [dbo].[EST_PROD_CPL] ENABLE TRIGGER [TRG_EST_PROD_CPL_EDELIVERY_SINC]
GO