I got the problem is when I run following command in Oracle, I encounter the error.
Truncate table mytable;
Errors:
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
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..
A typical approach to delete many rows with many constraints is as follows:
mytable_new
with all the columns but without constrains (or create constraints disabled);mytable
to mytable_new
.mytable_new
to see that everything is ok.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.