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

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

   TYPE T_TXN_NUM IS TABLE OF SIEBEL_PURGE.PURGE_MEM_TXN.TXN_NUM%TYPE;

   TYPE T_ITEM_NUM IS TABLE OF SIEBEL_PURGE.PURGE_MEM_TXN.ITEM_NUM%TYPE;

   ARR_MEM_ID     T_MEM_ID;
   ARR_TXN_NUM    T_TXN_NUM;
   ARR_ITEM_NUM   T_ITEM_NUM;
   LOG_ROW_ID   NUMBER := 0;
   ROW_COUNT    NUMBER := 0;

   CURSOR C1
   IS
      SELECT /*+ parallel(A,5) FULL(A) */ A.MEMBER_ID,
                'PAC'
             || LPAD (SUBSTR (LPAD (A.MEM_NUM, 12, 0), -12), 12, 0)
             || TO_CHAR (B.PURGE_DATE, 'MMDDYYYY')
             || DBMS_RANDOM.STRING ('X', 5)
             || 'TX'
                TXN_NUM,
                'PAC'
             || LPAD (SUBSTR (LPAD (A.MEM_NUM, 12, 0), -12), 12, 0)
             || TO_CHAR (B.PURGE_DATE, 'MMDDYYYY')
             || DBMS_RANDOM.STRING ('X', 5)
             || 'AI'
                ITEM_NUM
        FROM SIEBEL_PURGE.PURGE_MEM_TXN A,
             (SELECT PURGE_DATE
                FROM SIEBEL_PURGE.PURGE_CONFIG
               WHERE ROW_ID = 1) B
       WHERE A.MEM_NUM 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 PURGE_MEM_TXN Part-6/6', SYSDATE
        FROM DUAL;

   COMMIT;

   OPEN C1;

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

      FORALL ROW IN ARR_MEM_ID.FIRST .. ARR_MEM_ID.LAST
         UPDATE SIEBEL_PURGE.PURGE_MEM_TXN
            SET TXN_NUM = ARR_TXN_NUM (ROW), ITEM_NUM = ARR_ITEM_NUM (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