IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_EST_PROD_CD_BARRA_CARGA')
BEGIN
	DROP TRIGGER TRG_EST_PROD_CD_BARRA_CARGA
END
GO


CREATE TRIGGER [dbo].[TRG_EST_PROD_CD_BARRA_CARGA] ON [dbo].[EST_PROD_CD_BARRA]
AFTER INSERT, UPDATE ,DELETE
AS 
BEGIN
 SET NOCOUNT ON
 /*Deletou o codigo de barra, e no houve update nem insert. Tira o lixo*/
   DELETE FROM CARGA  
       FROM est_prod_cd_barra_carga CARGA 
  	      JOIN DELETED ON DELETED.CD_EMP   = CARGA.CD_EMP
  					  AND DELETED.CD_PROD = CARGA.CD_PROD
					  AND DELETED.CD_BARRA = CARGA.CD_BARRA	
   WHERE DELETED.CD_EMP = 1 
   
 /* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ 
-- INSERE O CD_BARRA NOVO 

	INSERT INTO est_prod_cd_barra_carga ( CD_EMP, CD_PROD, CD_BARRA) 
 	SELECT DISTINCT
			INSERTED.CD_EMP
			,INSERTED.CD_PROD
			,INSERTED.CD_BARRA
	  FROM INSERTED
	 WHERE INSERTED.CD_EMP = 1 
	 AND INSERTED.nao_exportar = 0 
	 AND NOT EXISTS (SELECT 1
						 FROM est_prod_cd_barra_carga barra
						WHERE INSERTED.CD_EMP   = barra.CD_EMP
						  AND INSERTED.CD_PROD = barra.CD_PROD
						  AND INSERTED.CD_BARRA  = barra.CD_BARRA 
					    )

END 

GO

ALTER TABLE [dbo].[EST_PROD_CD_BARRA] ENABLE TRIGGER [TRG_EST_PROD_CD_BARRA_CARGA]
GO