Truncate table in Oracle getting errors

后端 未结 9 1282
忘了有多久
忘了有多久 2021-02-02 08:11

I got the problem is when I run following command in Oracle, I encounter the error.

Truncate table mytable;

Errors:

         


        
相关标签:
9条回答
  • 2021-02-02 09:05

    As mentioned by the error message, you cannot truncate a table that is referenced by enabled foreign keys. If you really want to use the truncate DDL command, disable the foreign key constraint first, run the truncate command, and enable it back.

    Reference: Difference between TRUNCATE, DELETE and DROP commands

    0 讨论(0)
  • 2021-02-02 09:08

    I had the similar issue and I sorted it out by the following scripts.

    begin
    for i in (select constraint_name, table_name from user_constraints a where a.owner='OWNER' and a.table_name not in
    (select b.table_name from user_constraints b where b.table_name like '%BIN%') 
      and  a.constraint_type not in 'P')
    LOOP
      execute immediate 'alter table '||i.table_name||' disable constraint '||i.constraint_name||'';
    end loop;
    end;
    /
    
    truncate table TABLE_1;
    truncate table TABLE_2;
    
    
    begin
    for i in (select constraint_name, table_name from user_constraints a where a.owner='OWNER' and a.table_name not in
    (select b.table_name from user_constraints b where b.table_name like '%BIN%') 
      and  a.constraint_type not in 'P')
    LOOP
      execute immediate 'alter table '||i.table_name||' enable constraint '||i.constraint_name||'';
    end loop;
    end;
    /
    

    This script will first disable all the Constraints. Truncates the data in the tables and then enable the contraints.

    Hope it helps.

    cheers..

    0 讨论(0)
  • 2021-02-02 09:12

    A typical approach to delete many rows with many constraints is as follows:

    • create mytable_new with all the columns but without constrains (or create constraints disabled);
    • copy whatever data you need from mytable to mytable_new.
    • enable constraints on mytable_new to see that everything is ok.
    • alter any constraints that reference mytable to reference mytable_new instead and see that everything is ok.
    • drop table mytable.
    • alter table mytable_new rename to mytable.

    It's far faster than deleting a million records with many slow constraints.

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