IF EXISTS ( SELECT 1 FROM SYS.TRIGGERS WHERE NAME = 'TRG_EST_PROD_INTEGRA_PROPZ_EVENTOS' )
BEGIN
	DROP TRIGGER TRG_EST_PROD_INTEGRA_PROPZ_EVENTOS
END
GO
CREATE TRIGGER TRG_EST_PROD_INTEGRA_PROPZ_EVENTOS ON EST_PROD
FOR INSERT, UPDATE 
AS  
  UPDATE A SET 
    A.ST_EVENTO = 4 
  FROM INSERTED I 
  JOIN INTEGRA_PROPZ_EVENTOS A ON(I.CD_PROD = A.CD_REGISTRO)
  WHERE A.ST_EVENTO = 3
  AND A.TABELA = 'EST_PROD'

  INSERT INTO INTEGRA_PROPZ_EVENTOS(TABELA, CD_EMP, CD_FILIAL, CD_REGISTRO, TP_EVENTO, DT_ULT_ALT, CD_USU, DT_DOCUMENTO)
  SELECT	
    'EST_PROD'                           AS TABELA,
	EST_PROD.CD_EMP                      AS CD_EMP,
	EST_PROD.CD_FILIAL                   AS CD_FILIAL,
	EST_PROD.CD_PROD                     AS CD_REGISTRO,
	1                                    AS TP_EVENTO,
	EST_PROD.DT_ULT_ATU                  AS DT_ULT_ALT,
	EST_PROD.CD_USU                      AS CD_USU,
	GETDATE()                            AS DT_DOCUMENTO	
  FROM INSERTED EST_PROD
  WHERE EST_PROD.CD_EMP = 1