 
/****** Object:  Trigger [TRG_RC_CREDIARIO_PARC_DT_FECHA_VENCTO]    Script Date: 06/24/2014 20:39:05 ******/
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_EST_TRIB_CONF_GRP_CPL_TRIB_PDV_PEND]'))
DROP TRIGGER [dbo].[TRG_EST_TRIB_CONF_GRP_CPL_TRIB_PDV_PEND]
GO

--SELECT * FROM EST_TRIB_CONF_GRP_CPL 
-------------------------------------INSERO EM RC_VD_CONV--------------------------------------
CREATE TRIGGER [dbo].[TRG_EST_TRIB_CONF_GRP_CPL_TRIB_PDV_PEND] ON [dbo].[EST_TRIB_CONF_GRP_CPL] FOR INSERT,UPDATE AS
BEGIN	
	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 I.CD_EMP, GRP.CD_REGIAO_FISCAL, GRP_PROD.CD_PROD, I.CD_CTR 
			FROM INSERTED I
				INNER JOIN EST_PROD_EST_TRIB_CONF_GRP GRP_PROD ON 
					I.CD_EMP = GRP_PROD.CD_EMP
					AND I.CD_CTR = GRP_PROD.CD_CTR
				INNER JOIN EST_TRIB_CONF_GRP GRP ON 
					I.CD_EMP = GRP.CD_EMP
					AND I.CD_CTR = GRP.CD_CTR				
			WHERE I.TP_MOV			= 0
					AND I.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 = I.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


