Truncate table in Oracle getting errors

You have to swap the TRUNCATE statement to DELETE statements, slower and logged but that's the way to do it when constraints are in place.

DELETE mytablename;

Either that or you can find the foreign keys that are referencing the table in question and disable them temporarily.

select 'ALTER TABLE '||TABLE_NAME||' DISABLE CONSTRAINT '||CONSTRAINT_NAME||';'
from user_constraints
where R_CONSTRAINT_NAME='<pk-of-table>';

Where pk-of-table is the name of the primary key of the table being truncated

Run the output of the above query. When this has been done, remember to enable them again, just change DISABLE CONSTRAINT into ENABLE CONSTRAINT


this page offers a very good solution ...

ORA-02266: unique/primary keys in table referenced by enabled foreign keys

I'm here copying from it the Solution:

  • Find the referenced ENABLED foreign key constraints and disable them.
  • truncate/delete from the table .
  • using any text editor .. just change disable to enable in the output you get from the query , then run it.

    select 'alter table '||a.owner||'.'||a.table_name||' disable constraint '||a.constraint_name||';'
    from all_constraints a, all_constraints b
    where a.constraint_type = 'R' and a.status='ENABLED'
    and a.r_constraint_name = b.constraint_name
    and a.r_owner  = b.owner
    and b.table_name = upper('YOUR_TABLE');
    

Tags:

Sql

Oracle

Plsql