IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_CG_FND_VERBA_RC_CRED_REVISAR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_CG_FND_VERBA_RC_CRED_REVISAR]
GO

--EXEC P_CG_FND_VERBA_RC_CRED_REVISAR
CREATE PROCEDURE P_CG_FND_VERBA_RC_CRED_REVISAR 
AS
SET NOCOUNT ON 
DECLARE @CD_EMP INT
DECLARE @CD_FILIAL INT
DECLARE @CD_RC_DEB INT
DECLARE @CD_DP_LANC INT
DECLARE @CD_FND_VERBA INT
DECLARE @CD_FND_VERBA_RECB INT
DECLARE @CD_FILIAL_VERBA INT
DECLARE @CD_USU INT
DECLARE @VLR_PGTO MONEY
DECLARE @DT_PAG DATETIME
DECLARE @HIST VARCHAR(200)

--Criando cursor para rodar por loja bloqueado
DECLARE ProcRecbtoVerba CURSOR FAST_FORWARD FOR 
SELECT
	c.CD_EMP,
	C.CD_FILIAL,
	C.CD_RC_DEB,
	C.CD_DP_LANC,
	CT.CD_FND_VERBA,
	CT.CD_FILIAL AS CD_FILIAL_VERBA ,
	C.VL_PGTO,
	'RECEBIMENTO DE DUPLICATA DE CONTRATO DE VERBA COMERCIAL' AS HIST,
	C.DT_PAG,
	C.CD_USU
FROM
	RC_DEB d INNER JOIN RC_CRED c ON
	d.CD_EMP = c.CD_EMP AND
	d.CD_FILIAL = c.CD_FILIAL AND
	d.CD_RC_DEB = c.CD_RC_DEB 
	INNER JOIN CG_FND_VERBA_RC_DEB_DUP_NR_CTR CT ON
	d.CD_EMP = CT.CD_EMP AND
	d.CD_FILIAL = CT.CD_FILIAL AND
	d.NR_DP  = CT.NR_DP AND
	d.ANO = CT.ANO 
	LEFT OUTER JOIN CG_FND_VERBA_RC_CRED CC ON
	c.CD_EMP = cc.CD_EMP AND
	c.CD_FILIAL = cc.CD_FILIAL AND
	c.CD_RC_DEB = cc.CD_RC_DEB 
WHERE
	cc.CD_RC_DEB  IS NULL
		
	OPEN ProcRecbtoVerba;
	FETCH NEXT FROM ProcRecbtoVerba INTO
									@CD_EMP,
									@CD_FILIAL,
									@CD_RC_DEB,
									@CD_DP_LANC,
									@CD_FND_VERBA,
									@CD_FILIAL_VERBA,
									@VLR_PGTO,
									@HIST,
									@DT_PAG,
									@CD_USU

	WHILE @@FETCH_STATUS = 0
		BEGIN
		PRINT 'Filial.: ' + CONVERT(CHAR(10), @CD_FILIAL, 112)  + CONVERT(CHAR(10), @CD_FND_VERBA, 112);

		SET @CD_FND_VERBA_RECB=ISNULL((SELECT
											COUNT(CD_FND_VERBA_RECB)
										FROM
											CG_FND_VERBA_RECB
										WHERE
											CD_EMP =@CD_EMP
											AND CD_FND_VERBA=@CD_FND_VERBA),0) + 1



		INSERT INTO CG_FND_VERBA_RECB
		SELECT
			@CD_EMP,
			@CD_FND_VERBA,
			@CD_FND_VERBA_RECB,
			@HIST,
			@VLR_PGTO,
			@DT_PAG,
			@DT_PAG,
			NULL,
			@CD_USU,
			0,
			0,
			0
		
		INSERT INTO CG_FND_VERBA_RC_CRED
		SELECT
			@CD_EMP,
			@CD_FILIAL,
			@CD_RC_DEB,
			@CD_DP_LANC,
			@CD_FND_VERBA,
			@CD_FND_VERBA_RECB,
			@CD_FILIAL_VERBA

	FETCH NEXT FROM ProcRecbtoVerba INTO
									@CD_EMP,
									@CD_FILIAL,
									@CD_RC_DEB,
									@CD_DP_LANC,
									@CD_FND_VERBA,
									@CD_FILIAL_VERBA,
									@VLR_PGTO,
									@HIST,
									@DT_PAG,
									@CD_USU
		END;

	CLOSE ProcRecbtoVerba;
	DEALLOCATE ProcRecbtoVerba;