Tuesday, May 17, 2011

Truncating empty temporary tables in Oracle for PeopleSoft applications

Truncating temporary tables is an effective way of resetting the high-watermark level in Oracle databases.

The following script just truncates those tables that are empty, as sometimes temporary tables containing data should not be deleted as the data may belong to processes in error.

DECLARE
   sqlstatement    VARCHAR2 (100);
   fulltablename   VARCHAR2 (40);
   t_count         NUMBER;

   CURSOR c1
   IS
      SELECT owner || '.' || table_name
        FROM all_tables a
       WHERE EXISTS (
                SELECT 'x'
                  FROM psrecdefn b
                 WHERE b.rectype = 7
                   AND a.table_name LIKE 'PS_' || b.recname || '%');
BEGIN
   OPEN c1;

   LOOP
      FETCH c1
       INTO fulltablename;

      EXIT WHEN c1%NOTFOUND;

      sqlstatement :=
            'select count(*) from dual where exists (select NULL from '
         || fulltablename
         || ')';

      EXECUTE IMMEDIATE sqlstatement
                   INTO t_count;

      IF t_count = 1
      THEN
         DBMS_OUTPUT.put_line ('WARNING: ' || fulltablename || ' has data, so it will not be truncated.');
      ELSE
         sqlstatement := 'truncate table ' || fulltablename;
         EXECUTE IMMEDIATE sqlstatement;

         DBMS_OUTPUT.put_line (fulltablename || ' was truncated');
      END IF;
   END LOOP;
END;


Note: the script should be run when no process is running, as it is not blocking the tables after checking if they are empty. So, between the check and the truncate, someone may insert data. In any case, changing the script to lock the table should not be difficult.

11 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Thank you friend for sharing this query to truncate temporary tables. Its really necessary to do this task on timely basis to improve the efficiency. I will also note down the point that you have mentioned above.
    sap migration

    ReplyDelete
  3. Thanks for the code. Adding a y/n option would be useful.

    ReplyDelete
  4. Hi im sanjay sap peoplesoft consultant. I just browsing blogs there I found your blog is interesting.. thank for posting… keep on postingpeopeoplesoft-techical

    ReplyDelete
  5. Hi im sanjay sap peoplesoft consultant. I just browsing blogs there I found your blog is interesting.. thank for posting… peoplesoft-techical

    ReplyDelete
  6. That was realy helpfull thanks.

    ReplyDelete
  7. I was just browsing blogs there I found your blog is interesting.. thanks for posting… keep on posting mypeoplesoft

    ReplyDelete
  8. Great job, appreciated well post like it, see peoplesoft community

    ReplyDelete
  9. Hi Javier, thanks for your code.

    ReplyDelete