CREATE OR REPLACE PROCEDURE APAGA_RETROBILL
(
P_CDFILIAL IN VARCHAR2,
P_NRRETROBILL IN NUMBER
)
AS
   V_IDSITRETROBILL VARCHAR2(1);
BEGIN
   SELECT MAX(IDSITRETROBILL)
     INTO V_IDSITRETROBILL
     FROM RETROBILL
    WHERE CDFILIAL = P_CDFILIAL
      AND NRRETROBILL = P_NRRETROBILL;
    
   IF V_IDSITRETROBILL IS NULL THEN
      /*Retrobill informado nao encontrado.*/
      RAISE_APPLICATION_ERROR(-20501, 'APPERRMSGSTR' ||  'APP-00022' || 'APPERRMSGEND', True);
   END IF;
   
   IF V_IDSITRETROBILL <> 'P' THEN
      /*Operacao bloqueada! Retrobill informado ja foi aprovado.*/
      RAISE_APPLICATION_ERROR(-20501, 'APPERRMSGSTR' ||  'APP-00023' || 'APPERRMSGEND', True);
   END IF;
   
   DELETE FROM ITRETROBILLCONS
    WHERE CDFILIAL = P_CDFILIAL 
      AND NRRETROBILL = P_NRRETROBILL;
    
   DELETE FROM ITRETROBILL
    WHERE CDFILIAL = P_CDFILIAL
      AND NRRETROBILL = P_NRRETROBILL;
   
   DELETE FROM RETROBILL
    WHERE CDFILIAL = P_CDFILIAL
      AND NRRETROBILL = P_NRRETROBILL;
END;
/