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

DECLARE
   TYPE T_ID IS TABLE OF SIEBEL_PURGE.P_INT_S_CONTACT_XM.PMT_ID%TYPE;

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

   TYPE T_TXN_ID IS TABLE OF SIEBEL_PURGE.P_INT_S_CONTACT_XM.PRV_TXN_ID%TYPE;

   ARR_ID       T_ID;
   ARR_MEM_ID   T_MEM_ID;
   ARR_TXN_ID   T_TXN_ID;
   LOG_ROW_ID   NUMBER := 0;
   ROW_COUNT    NUMBER := 0;

   CURSOR C1
   IS
      SELECT /*+ parallel(a,12) full(a) index_ffs(t,s_loy_txn_150710A) parallel_index(t,s_loy_txn_150710A,12) */ A.ROW_ID, T.MEMBER_ID, A.X_SP_MEMBER_NUM
        FROM SIEBEL.S_CONTACT_XM A
             INNER JOIN SIEBEL.S_LOY_TXN T ON A.X_SP_MEMBER_NUM = T.ROW_ID
       WHERE T.X_PURGE_FLG IS NOT NULL;
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, 'Populate P_INT_S_CONTACT_XM', SYSDATE FROM DUAL;

   COMMIT;

   OPEN C1;

   LOOP
      --FETCH C1 BULK COLLECT INTO ARR_ID, ARR_MEM_ID, ARR_TXN_ID LIMIT 1000;
	  FETCH C1 BULK COLLECT INTO ARR_ID, ARR_MEM_ID, ARR_TXN_ID LIMIT 50;

      FORALL ROW IN ARR_ID.FIRST .. ARR_ID.LAST
         INSERT
           INTO SIEBEL_PURGE.P_INT_S_CONTACT_XM (MEM_ID, PMT_ID, PRV_TXN_ID)
         VALUES (ARR_MEM_ID (ROW), ARR_ID (ROW), ARR_TXN_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