How to drop list of table from a schema in Oracle?

前端 未结 2 1052
粉色の甜心
粉色の甜心 2021-01-24 05:05

My Oracle scott schema contains table list like that

\'prefix_A\'
\'prefix_B\'
\'prefix_C\'
\'A\'
\'B\'
\'C\'

Now i want to drop list of tables

相关标签:
2条回答
  • 2021-01-24 05:13

    I used this to disable constraints, drop constraints and delete the tables.

     -- disable constraints on tables
    BEGIN
      FOR c IN
      (SELECT c.owner, c.table_name, c.constraint_name
       FROM user_constraints c, user_tables t
       WHERE c.table_name = t.table_name 
       AND t.table_name like 'WF_%'
       AND c.status = 'ENABLED'
       ORDER BY c.constraint_type DESC)
      LOOP
        dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name);
      END LOOP;
    END;             
    
    -- drop the constraints
    begin
        for r in ( select table_name, constraint_name
                   from user_constraints where
                   table_name like 'WF_%' )
        loop
            execute immediate 'alter table '||r.table_name
                              ||' drop constraint '||r.constraint_name;
        end loop;
    end loop;
    
    -- drop the tables
    begin
         for trec in ( select table_name
                       from user_tables
                       where table_name like 'WF_%' )
         loop
             execute immediate 'drop table '||trec.table_name|| ' purge';
         end loop;
    end;
    
    0 讨论(0)
  • 2021-01-24 05:32

    Use dynamic SQL driving off the data dictionary.

    begin
         for trec in ( select table_name
                       from user_tables
                       where table_name like 'PREFIX\_%' escape `\' )
         loop
             dbms_output.put_line('dropping table ' || trec.table_name);
             execute immediate 'drop table '||trec.table_name;
         end loop;
    end;
    

    It's a good idea to be precise with the LIKE clause; using the escape keyword to ensure underscores aren't treated as wildcards. Alternatively use substr(table_name, 1, 7) = 'PREFIX_'.

    Dropping the wrong table isn't a disaster provided you're working on 10g or later and the RECYCLE BIN is enabled, but it's still better not to. Obviously you wouldn't run code like this in Production, but you would use the principle to generate a script of drop statements.

    The above code doesn't handle dependencies. If you have foreign keys referencing the prefixed tables and you want to force the dropping of the tables use this additional logic:

         execute immediate 'drop table '|| trec.table_name ||' cascade constraint';
    

    This drops the foreign key constraints but leaves the (formerly) dependent tables.

    0 讨论(0)
提交回复
热议问题