--Author: Venkata Potluri
--Date: June 12, 2015

--16.00 mins in New QA

DECLARE
   LOG_ROW_ID   NUMBER := 0;
   ROW_COUNT    NUMBER := 0;
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 TEMP_TXN_XPF', SYSDATE FROM DUAL;

   COMMIT;

   EXECUTE IMMEDIATE 'TRUNCATE TABLE SIEBEL_PURGE.TEMP_TXN_XPF';

   BEGIN
      EXECUTE IMMEDIATE 'DROP INDEX SIEBEL_PURGE.TEMP_TXN_XPF_U1';
   EXCEPTION
      WHEN OTHERS
      THEN
         DBMS_OUTPUT.PUT_LINE (
            'Index SIEBEL_PURGE.TEMP_TXN_XPF_U1 doesn''t exist.');
   END;

   INSERT /*+ APPEND */
         INTO  SIEBEL_PURGE.TEMP_TXN_XPF (TXN_ID)
      SELECT /*+ PARALLEL(A,10) */
            ROW_ID
        FROM SIEBEL.S_LOY_TXN A
       WHERE X_PURGE_FLG = 'Y';

   ROW_COUNT := ROW_COUNT + SQL%ROWCOUNT;

   COMMIT;

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

   COMMIT;
END;
/

QUIT