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

-------------------------------------INSERO EM RC_VD_CONV--------------------------------------
CREATE TRIGGER [dbo].[TRG_EST_TRIB_CONF_GRP_TRIB_PDV_PEND] ON [dbo].EST_TRIB_CONF_GRP FOR INSERT,UPDATE AS
BEGIN	
	/* Pode ser aprimorada para um unico insert select */
	DECLARE @CD_EMP		INT
	DECLARE @CD_PROD	INT	
	DECLARE @CD_CTR		INT
	DECLARE @CD_REGIAO_FISCAL INT
	SET NOCOUNT ON	 
		DECLARE RS_TRIB CURSOR FAST_FORWARD	FOR	
			SELECT GRP.CD_EMP, I.CD_REGIAO_FISCAL, GRP.CD_PROD, GRP.CD_CTR 
			FROM INSERTED I
				INNER JOIN EST_PROD_EST_TRIB_CONF_GRP GRP ON 
					I.CD_EMP = GRP.CD_EMP
					AND I.CD_CTR = GRP.CD_CTR	
				INNER JOIN EST_TRIB_CONF_GRP_CPL GRP_CPL ON 
					GRP.CD_EMP = GRP_CPL.CD_EMP
					AND GRP.CD_CTR = GRP_CPL.CD_CTR			
			WHERE GRP_CPL.TP_MOV		= 0
					AND GRP_CPL.TP_TRANSA	= 1
					AND EXISTS (SELECT F.CD_EMP
								FROM PRC_FILIAL F INNER JOIN GLB_CID CID ON
									F.CD_CID = CID.CD_CID 
								WHERE	CID.UF COLLATE SQL_Latin1_General_CP1_CI_AS = GRP_CPL.UF COLLATE SQL_Latin1_General_CP1_CI_AS)	
										  				
		OPEN RS_TRIB
		FETCH NEXT FROM RS_TRIB INTO @CD_EMP, @CD_REGIAO_FISCAL, @CD_PROD, @CD_CTR
		WHILE @@FETCH_STATUS=0
			BEGIN
				IF NOT EXISTS (SELECT P.CD_EMP 
								FROM EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST_PEND P
								WHERE P.CD_EMP = @CD_EMP
										AND P.CD_REGIAO_FISCAL = @CD_REGIAO_FISCAL
										AND P.CD_PROD = @CD_PROD
										AND P.CD_CTR  = @CD_CTR)
					BEGIN							 
						INSERT INTO EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST_PEND
							VALUES (@CD_EMP, @CD_REGIAO_FISCAL, @CD_PROD, @CD_CTR, GETDATE())
					END
				FETCH NEXT FROM RS_TRIB INTO @CD_EMP, @CD_REGIAO_FISCAL, @CD_PROD, @CD_CTR
			END
		CLOSE RS_TRIB;	
		DEALLOCATE RS_TRIB;
END

