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

DECLARE
   TYPE T_MEM_ID IS TABLE OF SIEBEL_PURGE.PURGE_MEM_TXN.MEMBER_ID%TYPE;

   TYPE T_TXN_COUNT
      IS TABLE OF SIEBEL_PURGE.PURGE_MEM_TXN.PURGE_TXN_COUNT%TYPE;

   ARR_MEM_ID      T_MEM_ID;
   ARR_TXN_COUNT   T_TXN_COUNT;
   LOG_ROW_ID      NUMBER := 0;
   ROW_COUNT       NUMBER := 0;

   CURSOR C1
   IS
        SELECT /*+ index_ffs(p,purge_mem_txn_150819b) parallel_index(p,purge_mem_txn_150819b,12) */
              T.MEMBER_ID, COUNT (*)
          FROM SIEBEL.S_LOY_TXN T
               INNER JOIN SIEBEL_PURGE.PURGE_MEM_TXN P
                  ON P.MEMBER_ID = T.MEMBER_ID AND P.UPDATED_FLG = 'T'
         WHERE T.X_PURGE_FLG IS NOT NULL
      GROUP BY T.MEMBER_ID;
        /*SELECT MEMBER_ID, COUNT (*)
    FROM SIEBEL.S_LOY_TXN
   WHERE     X_PURGE_FLG IS NOT NULL
         AND MEMBER_ID IN (SELECT MEMBER_ID
                             FROM SIEBEL_PURGE.PURGE_MEM_TXN
                            WHERE UPDATED_FLG = 'T')
GROUP BY MEMBER_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, 'Update PURGE_MEM_TXN Part-3/6', SYSDATE FROM DUAL;

   COMMIT;

   OPEN C1;

   LOOP
      --FETCH C1 BULK COLLECT INTO ARR_MEM_ID, ARR_TXN_COUNT LIMIT 10000;
	  FETCH C1 BULK COLLECT INTO ARR_MEM_ID, ARR_TXN_COUNT LIMIT 50;

      FORALL ROW IN ARR_MEM_ID.FIRST .. ARR_MEM_ID.LAST
         UPDATE SIEBEL_PURGE.PURGE_MEM_TXN
            SET PURGE_TXN_COUNT = ARR_TXN_COUNT (ROW)
          WHERE MEMBER_ID = ARR_MEM_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