--Author: Venkata Potluri
--Date: May 08, 2015

DECLARE
   TYPE T_MEM_ID IS TABLE OF SIEBEL.S_LOY_ACRL_ITM.MEMBER_ID%TYPE;

   TYPE T_ACRL_ID IS TABLE OF SIEBEL.S_LOY_ACRL_ITM.ROW_ID%TYPE;

   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 T_MEM_ID, ACRL_ID FROM SIEBEL_PURGE.FIX_ACRL_MEM_ID;

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;

   INSERT INTO SIEBEL_PURGE.PURGE_LOG (ROW_ID, PROCESS_NAME, START_TIME)
      SELECT LOG_ROW_ID, 'Fix S_LOY_ACRL_ITM MEMBER_IDs Part-2/2', SYSDATE
        FROM DUAL;

   COMMIT;

   OPEN C1;

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

      FORALL ROW IN ARR_ACRL_ID.FIRST .. ARR_ACRL_ID.LAST
         UPDATE SIEBEL.S_LOY_ACRL_ITM
            SET MEMBER_ID = ARR_MEM_ID (ROW)
          WHERE ROW_ID = ARR_ACRL_ID (ROW);

      ROW_COUNT := ROW_COUNT + SQL%ROWCOUNT;

      UPDATE SIEBEL_PURGE.PURGE_LOG
         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
      SET END_TIME = SYSDATE, PROCESSED_ROWS = ROW_COUNT
    WHERE ROW_ID = LOG_ROW_ID;

   COMMIT;
END;
/

QUIT