Drop all tables in a given schema

sometimes you come into a situation where you have to drop all tables in a given schema. The easiest way is to delete the user and recreate him again but when lacking system privileges you will look for another way. I’ll find the following very handy and will delete all specified db objects….

BEGIN

 FOR cur_rec IN (SELECT object_name, object_type

FROM user_objects

                    WHERE object_type IN

                             (‘TABLE’,

                              ‘VIEW’,

                              ‘PACKAGE’,

                              ‘PROCEDURE’,

                              ‘FUNCTION’,

                              ‘SEQUENCE’,

                              ‘SYNONYM’

                             ))

   LOOP

      BEGIN

         IF cur_rec.object_type = ‘TABLE’

         THEN

            EXECUTE IMMEDIATE    ‘DROP ‘

                              || cur_rec.object_type

                              || ‘ “‘

                              || cur_rec.object_name

                              || ‘” CASCADE CONSTRAINTS’;

         ELSE

            EXECUTE IMMEDIATE    ‘DROP ‘

                              || cur_rec.object_type

                              || ‘ “‘

                              || cur_rec.object_name

                              || ‘”‘;

         END IF;

      EXCEPTION

         WHEN OTHERS

         THEN

            DBMS_OUTPUT.put_line (   ‘FAILED: DROP ‘

                                  || cur_rec.object_type

                                  || ‘ “‘

                                  || cur_rec.object_name

                                  || ‘”‘

                                 );

      END;

   END LOOP;

END;

/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.