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

DECLARE
   TYPE T_TXN_ID IS TABLE OF SIEBEL_PURGE.FIX_REDM_MEM_ID.TXN_ID%TYPE;

   TYPE T_TMEM_ID IS TABLE OF SIEBEL_PURGE.FIX_REDM_MEM_ID.T_MEM_ID%TYPE;

   TYPE T_REDM_ID IS TABLE OF SIEBEL_PURGE.FIX_REDM_MEM_ID.REDM_ID%TYPE;

   TYPE T_RMEM_ID IS TABLE OF SIEBEL_PURGE.FIX_REDM_MEM_ID.R_MEM_ID%TYPE;


   ARR_TXN_ID    T_TXN_ID;
   ARR_TMEM_ID   T_TMEM_ID;
   ARR_REDM_ID   T_REDM_ID;
   ARR_RMEM_ID   T_RMEM_ID;
   LOG_ROW_ID    NUMBER := 0;
   ROW_COUNT     NUMBER := 0;

   CURSOR C1
   IS
      --SELECT /*+ index_ffs(t,temp_txn_mem_u1) parallel(r,10) */ T.TXN_ID,
	  SELECT /*+ index_ffs(t,temp_txn_mem_u1) parallel(r,5) */ T.TXN_ID,
             T.T_MEM_ID,
             R.ROW_ID,
             R.MEMBER_ID
        FROM SIEBEL_PURGE.TEMP_TXN_MEM T
             INNER JOIN SIEBEL.S_LOY_RDM_ITM R ON T.TXN_ID = R.TXN_ID
       WHERE T.T_MEM_ID <> R.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, 'Fix S_LOY_RDM_ITM MEMBER_IDs Part-1/2', SYSDATE
        FROM DUAL;

   COMMIT;

   OPEN C1;

   LOOP
      FETCH C1
         BULK COLLECT INTO ARR_TXN_ID,
              ARR_TMEM_ID,
              ARR_REDM_ID,
              ARR_RMEM_ID
         --LIMIT 1000;
			LIMIT 50;
      FORALL ROW IN ARR_REDM_ID.FIRST .. ARR_REDM_ID.LAST
         INSERT INTO SIEBEL_PURGE.FIX_REDM_MEM_ID (TXN_ID,
                                                   T_MEM_ID,
                                                   REDM_ID,
                                                   R_MEM_ID)
              VALUES (ARR_TXN_ID (ROW),
                      ARR_TMEM_ID (ROW),
                      ARR_REDM_ID (ROW),
                      ARR_RMEM_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