--Author: Venkata Potluri
--Date: July 16, 2015

--M - update PURGE_MEM_TXN; Need to fix member number, pr_con_id
--T - update PURGE_MEM_TXN; Need to rerun the txn_counts and calcs
--Y - update PURGE_MEM_REDEEMABLE
--Y - update PURGE_MEM_INFO

DECLARE
   LOG_ROW_ID    NUMBER := 0;
   ROW_COUNT     NUMBER := 0;
   C_ROW_COUNT   NUMBER := 0;

   CURSOR C1
   IS
      SELECT M.ROW_ID TO_MEM_ID, S.X_FROM_LOY_MEMBER_ID FROM_MEM_ID
        FROM SIEBEL.S_LOY_MEMBER M
             INNER JOIN SIEBEL.S_SRV_REQ_LOYX S ON S.LOY_MEMBER_ID = M.ROW_ID
       WHERE M.ROW_ID IN
                (SELECT DISTINCT LOY_MEMBER_ID
                   FROM SIEBEL.S_SRV_REQ_LOYX
                  WHERE X_FROM_LOY_MEMBER_ID IN
                           (SELECT MEMBER_ID
                              FROM SIEBEL_PURGE.PURGE_MEM_TXN
                             WHERE MEM_NUM IS 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, 'Fix NULL MEM_NUMs', SYSDATE FROM DUAL;

   COMMIT;

   FOR CR IN C1
   LOOP
      UPDATE SIEBEL.S_LOY_TXN
         SET MEMBER_ID = CR.TO_MEM_ID
       WHERE MEMBER_ID = CR.FROM_MEM_ID;

      UPDATE SIEBEL.S_LOY_ACRL_ITM
         SET MEMBER_ID = CR.TO_MEM_ID
       WHERE MEMBER_ID = CR.FROM_MEM_ID;

      UPDATE SIEBEL.S_LOY_RDM_ITM
         SET MEMBER_ID = CR.TO_MEM_ID
       WHERE MEMBER_ID = CR.FROM_MEM_ID;

      UPDATE SIEBEL_PURGE.PURGE_MEM_TXN
         SET UPDATED_FLG = 'T'
       WHERE MEMBER_ID = CR.TO_MEM_ID;

      C_ROW_COUNT := SQL%ROWCOUNT;

      IF (C_ROW_COUNT = 0)
      THEN
         UPDATE SIEBEL_PURGE.PURGE_MEM_TXN
            SET MEMBER_ID = CR.TO_MEM_ID, UPDATED_FLG = 'M'
          WHERE MEMBER_ID = CR.FROM_MEM_ID;
      ELSE
         DELETE FROM SIEBEL_PURGE.PURGE_MEM_TXN
               WHERE MEMBER_ID = CR.FROM_MEM_ID;
      END IF;

      ROW_COUNT := ROW_COUNT + 1;

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

      COMMIT;
   END LOOP;

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

   COMMIT;
END;
/

QUIT