create or replace PROCEDURE FCT_CANC_VENCPREV_CONT
  (P_NRORG IN NUMBER,
   P_NRSEQCONTRATO IN NUMBER)
AS
  V_VERIFICAMEDICAO NUMBER;
BEGIN

   /*PROCEDEURE PARA CANCELAR/DELETAR OS VENCIMENTOS ANTES DE CRIAR OS NOVOS*/
   
   FOR C_VENCDEL IN (SELECT NRVENCPREVCONT
                       FROM FCT_VENCPREVCONT
                      WHERE NRSEQCONTRATO = P_NRSEQCONTRATO
                        AND NRAPURACAO IS NULL
                        AND NRORG = P_NRORG)LOOP

      SELECT COUNT(*) AS QTMEDIC
        INTO V_VERIFICAMEDICAO
        FROM FCT_MEDICAOAPU
       WHERE NRSEQCONTRATO = P_NRSEQCONTRATO
         AND NRVENCPREVCONT = C_VENCDEL.NRVENCPREVCONT
         AND NRORG = P_NRORG;

      IF(V_VERIFICAMEDICAO = 0) THEN
         SELECT COUNT(*) AS QTMEDIC
           INTO V_VERIFICAMEDICAO
           FROM FCT_MEDICAOAPU M, FCT_ITVENCPREVCONT IT
          WHERE M.NRSEQCONTRATO = P_NRSEQCONTRATO
            AND M.NRITVENCPREVCONT = IT.NRITVENCPREVCONT
            AND IT.NRVENCPREVCONT = C_VENCDEL.NRVENCPREVCONT
            AND M.NRORG = P_NRORG;
      END IF;

      IF(V_VERIFICAMEDICAO = 0) THEN

          DELETE FROM FCT_VENCPREVCONT
           WHERE NRSEQCONTRATO = P_NRSEQCONTRATO
             AND NRVENCPREVCONT = C_VENCDEL.NRVENCPREVCONT
             AND NRAPURACAO IS NULL
             AND NRORG = P_NRORG;
      END IF;
   END LOOP;
END;