CREATE OR REPLACE PROCEDURE REPLICA_PRATO_CARDBASE
(
   P_NRCARDAPIOBASE IN NUMBER,
   P_NRCOMPCARDBASE IN NUMBER,
   P_NRORG IN NUMBER,
   P_CDOPERADOR IN VARCHAR2,
   P_DOM IN VARCHAR2,
   P_SEG IN VARCHAR2,
   P_TER IN VARCHAR2,
   P_QUA IN VARCHAR2,
   P_QUI IN VARCHAR2,
   P_SEX IN VARCHAR2,
   P_SAB IN VARCHAR2,
   P_SUBTITUIR IN VARCHAR2 DEFAULT 'S'
)
AS   
   V_NRDIACARDBASEORI NUMBER;
   V_NRSEMANA NUMBER;
   V_NRDIASEMANA NUMBER;
   V_NRCONFIGCARDBASEORI NUMBER;
BEGIN
   SELECT MAX(C.NRDIACARDBASE), MAX(C.NRCONFIGCARDBASE), MAX(D.NRSEMANA), MAX(D.NRDIASEMANA)
     INTO V_NRDIACARDBASEORI, V_NRCONFIGCARDBASEORI, V_NRSEMANA, V_NRDIASEMANA
     FROM COMPCARDBASE C
          INNER JOIN DIACARDBASE D ON D.NRDIACARDBASE = C.NRDIACARDBASE
    WHERE C.NRCOMPCARDBASE = P_NRCOMPCARDBASE
      AND C.NRCARDAPIOBASE = P_NRCARDAPIOBASE;
   
   IF V_NRDIACARDBASEORI IS NOT NULL AND 
      V_NRCONFIGCARDBASEORI IS NOT NULL THEN
      FOR C_DIAS IN
      (
         SELECT NRDIACARDBASE
           FROM DIACARDBASE
          WHERE NRCARDAPIOBASE = P_NRCARDAPIOBASE
            AND ((NRSEMANA <> V_NRSEMANA) OR (NRDIASEMANA <> V_NRDIASEMANA))
            AND ((NRDIASEMANA = 1 AND P_DOM = 'S') OR
                 (NRDIASEMANA = 2 AND P_SEG = 'S') OR
                 (NRDIASEMANA = 3 AND P_TER = 'S') OR
                 (NRDIASEMANA = 4 AND P_QUA = 'S') OR
                 (NRDIASEMANA = 5 AND P_QUI = 'S') OR
                 (NRDIASEMANA = 6 AND P_SEX = 'S') OR
                 (NRDIASEMANA = 7 AND P_SAB = 'S'))
      ) LOOP
         COPIA_PRATO_CARDBASE( P_NRCARDAPIOBASE, P_NRCOMPCARDBASE, C_DIAS.NRDIACARDBASE, V_NRCONFIGCARDBASEORI, P_NRORG, P_CDOPERADOR, P_SUBTITUIR );
      END LOOP;
   END IF;
END;
/