IF OBJECT_ID ('TRG_EST_PROD_NCM_CADASTRO_PDV_PEND', 'TR') IS NOT NULL
BEGIN
	DROP TRIGGER TRG_EST_PROD_NCM_CADASTRO_PDV_PEND
END
GO

CREATE TRIGGER [dbo].[TRG_EST_PROD_NCM_CADASTRO_PDV_PEND] ON [dbo].[EST_PROD_NCM_CADASTRO] FOR INSERT,UPDATE AS
BEGIN	
	BEGIN TRY

		 INSERT INTO EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST_PEND
		 SELECT DISTINCT PROD.CD_EMP, REG.CD_REGIAO_FISCAL, PROD.CD_PROD, 0 AS CD_CTR, GETDATE() 
		 FROM INSERTED NCM
		 INNER JOIN EST_PROD PROD ON NCM.NR_NCM = PROD.NR_NCM
		 CROSS APPLY (SELECT DISTINCT CD_REGIAO_FISCAL 
		 			 FROM EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST) REG
		 WHERE PROD.STS_PROD <> 1
		 AND NOT EXISTS (SELECT 1 
		 								FROM EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST_PEND P
		 								WHERE P.CD_EMP = PROD.CD_EMP
		 										AND P.CD_REGIAO_FISCAL = REG.CD_REGIAO_FISCAL
		 										AND P.CD_PROD = PROD.CD_PROD
		 										AND P.CD_CTR  = 0)
	END TRY
	BEGIN CATCH
		PRINT 1
	END CATCH
END


