CREATE OR REPLACE PROCEDURE GERA_PREVPAX_PROD
(P_CDFILIAL IN VARCHAR2,
 P_CDFILIPROC IN VARCHAR2,
 P_DATAINI IN DATE,
 P_DATAFIN IN DATE,
 P_SUBSTITUI_JA_GERADOS IN VARCHAR2,
 P_CDOPERADOR IN VARCHAR2,
 P_NRORG IN NUMBER DEFAULT 1,
 P_NRLISTAERROS IN OUT NUMBER
)
AS   
   V_SEQ VARCHAR2(20);   
   V_CDCIA VARCHAR2(4);
   V_CONTADOR NUMBER;   
BEGIN
   /*Busca todas as companhias da malha aerea*/
   FOR C_DATAS IN
   (
   SELECT DT.DTDATA
     FROM DATA DT
    WHERE DT.DTDATA BETWEEN P_DATAINI AND P_DATAFIN
    ORDER BY DT.DTDATA
   ) LOOP     
      /* Gera dados da malha para a data informada */
      GERA_PREVPAXDATA_PROD(P_CDFILIAL, P_CDFILIPROC, C_DATAS.DTDATA, P_SUBSTITUI_JA_GERADOS, P_CDOPERADOR, P_NRORG, P_NRLISTAERROS);

   END LOOP;

   IF P_NRLISTAERROS IS NOT NULL THEN
      RETURN;
   END IF;

   SELECT COUNT(1)
     INTO V_CONTADOR
     FROM PREVPAXPRODM
    WHERE CDFILIAL = P_CDFILIAL
      AND DTPREVISAOPROD BETWEEN P_DATAINI AND P_DATAFIN;
      
   IF V_CONTADOR <= 0 THEN
      /* Nao ha dados na malha aerea para o periodo informado. */
      RAISE_APPLICATION_ERROR(-20000, 'APPERRMSGSTR' || 'APP-00059' || 'APPERRMSGEND');      
   END IF;
END;
/