SQL: delete all the data from all available tables

前端 未结 9 1145
小蘑菇
小蘑菇 2020-12-09 08:43

I am using oracle DB to maintain more than 30 tables, how can I delete all the data from all the tables? I only want to delete the data but not drop the tables.

9条回答
  •  执笔经年
    2020-12-09 09:15

    I created this stored proc, using the answers mentioned above. This works perfectly without any errors or exceptions.

        create or replace PROCEDURE DELETE_ALL_DATA
    AS 
    cursor r1 is select * from user_constraints;
    cursor r2 is select * from user_tables;
    cursor r3 is select * from user_constraints;
    cursor r4 is select * from user_tables;
    
    BEGIN
    
        FOR c1 IN r1
      loop
        for c2 in r2
        loop
            begin
           if c1.table_name = c2.table_name and c1.status = 'ENABLED' THEN
            dbms_utility.exec_ddl_statement('alter table ' || c1.owner || '.' || c1.table_name || ' disable constraint ' || c1.constraint_name);
           end if;
            EXCEPTION
             WHEN NO_DATA_FOUND
               THEN
               continue;
             WHEN OTHERS 
               THEN
               continue;
               end;
        end loop;
      END LOOP;
    
        FOR T in (SELECT table_name FROM user_tables) LOOP
          begin
          EXECUTE IMMEDIATE 'TRUNCATE TABLE '||T.table_name;
          EXCEPTION
             WHEN NO_DATA_FOUND
               THEN
               continue;
             WHEN OTHERS 
               THEN
               continue;
               end;
        END LOOP;
    
        FOR c1 IN r3
      loop
        for c2 in r4
        loop
            begin
           if c1.table_name = c2.table_name and c1.status = 'DISABLED' THEN
            dbms_utility.exec_ddl_statement('alter table ' || c1.owner || '.' || c1.table_name || ' enable constraint ' || c1.constraint_name);
           end if;
            EXCEPTION
             WHEN NO_DATA_FOUND
               THEN
               continue;
             WHEN OTHERS 
               THEN
               continue;
               end;
        end loop;
      END LOOP;
    
        commit;
    END DELETE_ALL_DATA;
    

提交回复
热议问题