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

CREATE TRIGGER [dbo].[TRG_EST_PROD_EDELIVERY_SINC] ON [dbo].[EST_PROD] 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.STS_PROD <> ISNULL(D.STS_PROD,0)
	AND I.STS_PROD 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

