 

IF EXISTS (SELECT * FROM SYS.procedures WHERE NAME = 'P_ATUALIZA_RC_CLI_CONV_DT_PROX_FECHA')
BEGIN
	DROP PROCEDURE P_ATUALIZA_RC_CLI_CONV_DT_PROX_FECHA 
END; 
GO 

CREATE PROCEDURE P_ATUALIZA_RC_CLI_CONV_DT_PROX_FECHA (@CD_CONV  INT = NULL )

WITH ENCRYPTION
AS 
SET NOCOUNT ON 
DECLARE @DIA_FAT  INT=NULL;
DECLARE @DIA_FAT2 INT=NULL;
DECLARE @DIA_FAT3 INT=NULL;
DECLARE @DT_PROX_FECHAMENTO DATETIME=NULL;
--DECLARE @CD_CONV INT=NULL;



BEGIN 
DECLARE C1 CURSOR 
FOR 
	SELECT DIA_FAT,
		   DIA_FAT2,
		   DIA_FAT3,
		   DT_PROX_FECHAMENTO,
		   CD_CONV 
	  FROM RC_CLI_CONV  
	 WHERE CD_EMP = 1
	   AND CD_CONV = CASE WHEN @CD_CONV IS NULL THEN RC_CLI_CONV.CD_CONV  
						  ELSE @CD_CONV
						  END;

OPEN C1;
FETCH NEXT FROM C1 INTO @DIA_FAT
					   ,@DIA_FAT2
					   ,@DIA_FAT3
					   ,@DT_PROX_FECHAMENTO
					   ,@CD_CONV;

WHILE @@FETCH_STATUS = 0 
	BEGIN 

PRINT 'INICIO - CAPTURANDO DT_PROX_FECHAMENTO :' + CONVERT(VARCHAR(50),GETDATE(),121)
			IF @DIA_FAT > 0 
				BEGIN
					IF @DIA_FAT <= DATEPART(DAY,GETDATE())
						BEGIN 
							SET @DT_PROX_FECHAMENTO = DATEADD(MONTH,1, DATEADD(DAY, DATEPART(DAY, GETDATE()) *-1 + @DIA_FAT, GETDATE()))
						END; 
				    ELSE 
						BEGIN 
							SET @DT_PROX_FECHAMENTO =  DATEADD(DAY,DATEPART(DAY,GETDATE())*-1 + @DIA_FAT,GETDATE())						
						END; 
				END; 



			IF @DIA_FAT2 > @DIA_FAT				
					IF @DIA_FAT2 <= DATEPART(DAY,GETDATE())
					BEGIN 
							SET @DT_PROX_FECHAMENTO =DATEADD(MONTH,1, DATEADD(DAY,DATEPART(DAY,GETDATE())*-1 + @DIA_FAT2,GETDATE()))
						END; 
				    ELSE 
						BEGIN 
							SET @DT_PROX_FECHAMENTO =  DATEADD(DAY,DATEPART(DAY,GETDATE())*-1 + @DIA_FAT2,GETDATE())						
						END; 



			IF @DIA_FAT3 > @DIA_FAT				
					IF @DIA_FAT3 <= DATEPART(DAY,GETDATE())
					BEGIN 
							SET @DT_PROX_FECHAMENTO =DATEADD(MONTH,1, DATEADD(DAY,DATEPART(DAY,GETDATE())*-1 + @DIA_FAT3,GETDATE()))
						END; 
				    ELSE 
						BEGIN 
							SET @DT_PROX_FECHAMENTO =  DATEADD(DAY,DATEPART(DAY,GETDATE())*-1 + @DIA_FAT3,GETDATE())						
						END; 


	UPDATE RC_CLI_CONV
	   SET DT_PROX_FECHAMENTO= CAST(CAST(@DT_PROX_FECHAMENTO AS DATE) AS DATETIME)
	      ,DT_ULT_ALT = GETDATE() 
	 WHERE CD_EMP = 1 
	   AND CD_CONV= @CD_CONV

PRINT 'FIM - P_ATUALIZA_RC_CLI_CONV_DT_PROX_FECHA: ' + CONVERT(VARCHAR(50),GETDATE(),121)
FETCH NEXT FROM C1 INTO @DIA_FAT 
     				   ,@DIA_FAT2
	    			   ,@DIA_FAT3
					   ,@DT_PROX_FECHAMENTO
					   ,@CD_CONV;

	END;
CLOSE C1;
DEALLOCATE C1;
END ; 