IF EXISTS (SELECT 1 FROM sys.objects WHERE [name] = N'TRG_EST_PROD_CD_BARRA_PMPF' AND [type] = 'TR')
BEGIN
      DROP TRIGGER TRG_EST_PROD_CD_BARRA_PMPF;
END;
GO

CREATE TRIGGER TRG_EST_PROD_CD_BARRA_PMPF ON EST_PROD_CD_BARRA
FOR INSERT, UPDATE ,DELETE
AS 
BEGIN
 SET NOCOUNT ON
 /*Deletou o codigo de barra, e no houve update nem insert. Tira o lixo*/
   DELETE FROM PMPF_CPL  
       FROM EST_PROD_PRECO_PMPF_CPL PMPF_CPL 
  	      JOIN DELETED ON DELETED.CD_EMP   = PMPF_CPL.CD_EMP
  					  AND DELETED.CD_BARRA = PMPF_CPL.EAN
   WHERE DELETED.CD_EMP = 1
   and not exists (select 1 from INSERTED)
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ 
   DELETE FROM PMPF_CPL  
     FROM EST_PROD_PRECO_PMPF_CPL PMPF_CPL 
	      JOIN DELETED ON DELETED.CD_EMP   = PMPF_CPL.CD_EMP
					  AND DELETED.CD_BARRA = PMPF_CPL.EAN
					 -- AND DELETED.CD_PROD  = PMPF_CPL.CD_PROD 
		 JOIN INSERTED  ON DELETED.CD_EMP  =  INSERTED.CD_EMP
					  AND DELETED.CD_BARRA <> INSERTED.CD_BARRA
					  --AND DELETED.CD_PROD  =  INSERTED.CD_PROD 
    WHERE DELETED.CD_EMP = 1
 /* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ 
-- INSERE O CD_BARRA NOVO 
	INSERT INTO EST_PROD_PRECO_PMPF_CPL ( CD_CTR, CD_EMP, CD_PROD, EAN, VLR_PMPF, LABORATORIO, APRESENTACAO, UF, CD_USU, DT_CAD) 
 	SELECT DISTINCT
			 N_ENC.CD_CTR
			,INSERTED.CD_EMP
			,INSERTED.CD_PROD
			,N_ENC.EAN
		    ,N_ENC.VLR_PMPF
			,N_ENC.LABORATORIO
			,N_ENC.APRESENTACAO
			,N_ENC.UF
			,N_ENC.CD_USU
			,N_ENC.DT_CAD
	  FROM EST_PROD_PRECO_PMPF_TBL N_ENC
	       JOIN EST_PROD_PRECO_PMPF ON N_ENC.CD_CTR = EST_PROD_PRECO_PMPF.CD_CTR AND EST_PROD_PRECO_PMPF.STS_TBL = 0
		   JOIN INSERTED ON N_ENC.EAN = INSERTED.CD_BARRA
	 WHERE INSERTED.CD_EMP = 1   
	   AND NOT EXISTS (SELECT *
						 FROM EST_PROD_PRECO_PMPF_CPL CPL
						WHERE INSERTED.CD_EMP   = CPL.CD_EMP
						  --AND INSERTED.CD_BARRA = CPL.EAN
						  AND INSERTED.CD_PROD  = CPL.CD_PROD
						  AND N_ENC.CD_CTR = CPL.CD_CTR
						  AND N_ENC.UF = CPL.UF
					    )

	DELETE FROM CPL_N_ENC
	  FROM EST_PROD_PRECO_PMPF_CPL_N_ENC CPL_N_ENC
	       JOIN EST_PROD_PRECO_PMPF_CPL ON CPL_N_ENC.EAN = EST_PROD_PRECO_PMPF_CPL.EAN
		   JOIN INSERTED ON CPL_N_ENC.EAN	= INSERTED.CD_BARRA
     WHERE INSERTED.CD_EMP = 1
END 
GO

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


