--Author: Venkata Potluri
--Date: April 04, 2015
--3:34:36 hours in DEV with bulk 10,000 for 78,622,640 updates
--12:51:28 hours in QA with bulk 50,000 for 254,056,774 updates

DECLARE
   TYPE T_ID IS TABLE OF SIEBEL.S_LOY_TXN.ROW_ID%TYPE;

   ARR_ID       T_ID;
   LOG_ROW_ID   NUMBER := 0;
   ROW_COUNT    NUMBER := 0;
   OK_TO_RUN    CHAR (1 CHAR) := 'N';

   CURSOR C1
   IS
        --SELECT /*+ FULL(A) PARALLEL(A,10) */
		SELECT /*+ FULL(A) PARALLEL(A,5) */
              A.ROW_ID
          FROM SIEBEL.S_LOY_TXN A
         WHERE     A.X_PURGE_FLG IS NULL
               AND A.TXN_DT < (SELECT PURGE_DATE
                                 FROM SIEBEL_PURGE.PURGE_CONFIG
                                WHERE ROW_ID = 1)
               AND NVL (A.PROCESS_DT, TO_DATE ('01-01-1970', 'MM-DD-YYYY')) <
                      (SELECT ADD_MONTHS (PURGE_DATE, 12)
                         FROM SIEBEL_PURGE.PURGE_CONFIG
                        WHERE ROW_ID = 1)
      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_TXN XPF Part-1/3', SYSDATE FROM DUAL;

   COMMIT;

   SELECT OKAY_TO_RUN
     INTO OK_TO_RUN
     FROM SIEBEL_PURGE.PURGE_CONFIG
    WHERE ROW_ID = 1;

   IF (OK_TO_RUN = 'Y')
   THEN
      OPEN C1;

      LOOP
         --FETCH C1 BULK COLLECT INTO ARR_ID LIMIT 5000;
		 FETCH C1 BULK COLLECT INTO ARR_ID LIMIT 50;

         FORALL ROW IN ARR_ID.FIRST .. ARR_ID.LAST
            UPDATE SIEBEL.S_LOY_TXN
               SET X_PURGE_FLG = 'Y'
             WHERE ROW_ID = ARR_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;

         SELECT OKAY_TO_RUN
           INTO OK_TO_RUN
           FROM SIEBEL_PURGE.PURGE_CONFIG
          WHERE ROW_ID = 1;

         EXIT WHEN OK_TO_RUN = 'N';
         EXIT WHEN C1%NOTFOUND;
      END LOOP;

      CLOSE C1;
   END IF;

   UPDATE SIEBEL_PURGE.PURGE_LOG
      SET END_TIME = SYSDATE, PROCESSED_ROWS = ROW_COUNT
    WHERE ROW_ID = LOG_ROW_ID;

   COMMIT;
END;
/

QUIT