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

DECLARE
   TYPE T_ATTR_ID IS TABLE OF SIEBEL_PURGE.P_INT_S_LOY_ATTR_ITM.ATTR_ID%TYPE;

   TYPE T_TXN_ID
      IS TABLE OF SIEBEL_PURGE.P_INT_S_LOY_ATTR_ITM.NEW_TXN_ID%TYPE;

   ARR_ATTR_ID   T_ATTR_ID;
   ARR_TXN_ID    T_TXN_ID;
   LOG_ROW_ID    NUMBER := 0;
   ROW_COUNT     NUMBER := 0;

   CURSOR C1
   IS
        SELECT /*+ parallel(P,12) full(P) index_ffs(A,S_LOY_ATTR_ITM_P1) parallel_index(A,S_LOY_ATTR_ITM_P1,12)*/
              P.ATTR_ID, P.NEW_TXN_ID
          FROM SIEBEL_PURGE.P_INT_S_LOY_ATTR_ITM P
               INNER JOIN SIEBEL.S_LOY_ATTR_ITM A ON A.ROW_ID = P.ATTR_ID
      ORDER BY A.ROWID;
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 S_LOY_ATTR_ITM', SYSDATE FROM DUAL;

   COMMIT;

   OPEN C1;

   LOOP
      FETCH C1 BULK COLLECT INTO ARR_ATTR_ID, ARR_TXN_ID LIMIT 10000;
	  --FETCH C1 BULK COLLECT INTO ARR_ATTR_ID, ARR_TXN_ID LIMIT 50;

      FORALL ROW IN ARR_ATTR_ID.FIRST .. ARR_ATTR_ID.LAST
         UPDATE SIEBEL.S_LOY_ATTR_ITM
            SET TXN_ID = ARR_TXN_ID (ROW)
          WHERE ROW_ID = ARR_ATTR_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