--Author: Venkata Potluri
--Date: Oct 20, 2015
--2 min

DECLARE
   TYPE T_ID
      IS TABLE OF SIEBEL_PURGE.P_INT_S_LOY_RDM_ITM_10012012.RDM_ID%TYPE;

   TYPE T_MEM_ID
      IS TABLE OF SIEBEL_PURGE.P_INT_S_LOY_RDM_ITM_10012012.MEM_ID%TYPE;

   TYPE T_ACRL_ID
      IS TABLE OF SIEBEL_PURGE.P_INT_S_LOY_RDM_ITM_10012012.PRV_ACRL_ID%TYPE;

   ARR_ID        T_ID;
   ARR_MEM_ID    T_MEM_ID;
   ARR_ACRL_ID   T_ACRL_ID;

   LOG_ROW_ID    NUMBER := 0;
   ROW_COUNT     NUMBER := 0;

   CURSOR C1
   IS
      SELECT R.MEMBER_ID, R.ROW_ID, R.ACCRUAL_ITEM_ID
        FROM SIEBEL.S_LOY_RDM_ITM R
             INNER JOIN SIEBEL.S_LOY_ACRL_ITM$A A
                ON     A.ROW_ID = R.ACCRUAL_ITEM_ID
                   AND R.CREATED BETWEEN TO_DATE ('10/14/2015', 'mm/dd/yyyy')
                                     AND TO_DATE ('10/18/2015', 'mm/dd/yyyy');
BEGIN
   SELECT CASE WHEN MAX (ROW_ID) IS NOT NULL THEN MAX (ROW_ID) + 1 ELSE 1 END
     INTO LOG_ROW_ID
     FROM SIEBEL_PURGE.PURGE_LOG_10012012;

   INSERT INTO SIEBEL_PURGE.PURGE_LOG_10012012 (ROW_ID,
                                                PROCESS_NAME,
                                                START_TIME)
      SELECT LOG_ROW_ID, 'Populate P_INT_S_LOY_RDM_ITM_10012012', SYSDATE
        FROM DUAL;

   COMMIT;

   OPEN C1;

   LOOP
      FETCH C1 BULK COLLECT INTO ARR_MEM_ID, ARR_ID, ARR_ACRL_ID LIMIT 50;

      FORALL ROW IN ARR_ID.FIRST .. ARR_ID.LAST
         INSERT INTO SIEBEL_PURGE.P_INT_S_LOY_RDM_ITM_10012012 (MEM_ID,
                                                                RDM_ID,
                                                                PRV_ACRL_ID,
                                                                TASK_NUM)
              VALUES (ARR_MEM_ID (ROW),
                      ARR_ID (ROW),
                      ARR_ACRL_ID (ROW),
                      1);

      ROW_COUNT := ROW_COUNT + SQL%ROWCOUNT;

      UPDATE SIEBEL_PURGE.PURGE_LOG_10012012
         SET PROCESSED_ROWS = ROW_COUNT
       WHERE ROW_ID = LOG_ROW_ID;

      COMMIT;

      EXIT WHEN C1%NOTFOUND;
   END LOOP;

   CLOSE C1;

   UPDATE SIEBEL_PURGE.PURGE_LOG_10012012
      SET END_TIME = SYSDATE, PROCESSED_ROWS = ROW_COUNT
    WHERE ROW_ID = LOG_ROW_ID;

   COMMIT;
END;
/

QUIT