如何删除也是孩子的父表?

时间:2019-04-04 01:04:47

标签: oracle sqlplus

我有两个表,两个表都互相引用主键作为外键,我想都将它们都删除,但不能。

我尝试过这个:

alter table my_table drop constraint cons_name;

那给了我:

ORA-02443:无法删除约束-不存在约束

1 个答案:

答案 0 :(得分:0)

假设您具有以下表格(Oracle 12c)...

create table table1 ( column1 primary key )
as
select level
from dual
connect by level <= 10 ;

create table table2 ( column1 primary key )
as
select level
from dual
connect by level <= 10 ;

alter table table1
add constraint fk1 
    foreign key ( column1 ) references table2( column1 ) ;

alter table table2
add constraint fk2 
    foreign key ( column1 ) references table1( column1 ) ;

如果要删除约束,请确保使用正确的 约束名称。

-- find the correct constraint names
select table_name, constraint_name, constraint_type
from user_constraints
where table_name in( 'TABLE1', 'TABLE2' ) ;

TABLE_NAME  CONSTRAINT_NAME  CONSTRAINT_TYPE  
TABLE2      SYS_C0021482     P                
TABLE1      SYS_C0021483     P                
TABLE1      FK1              R                
TABLE2      FK2              R  

-- fails: constraint name correct, table name wrong
SQL> alter table table1 drop constraint SYS_C0021482;
ORA-02443: Cannot drop constraint  - nonexistent constraint

-- fails: need to disable/remove the FK constraint first
SQL> alter table table1 drop constraint SYS_C0021483;
ORA-02273: this unique/primary key is referenced by some foreign keys

-- okay
SQL> alter table table1 drop constraint FK1 ;
Table TABLE1 altered.

如果您只想删除两个表,包括所有约束,请使用...

SQL> drop table table1 cascade constraints purge ;

Table TABLE1 dropped.

SQL> drop table table2 cascade constraints purge ;

Table TABLE2 dropped.

检查:

-- any constraints left? no.
SQL> select table_name, constraint_name, constraint_type
  2  from user_constraints
  3  where table_name in( 'TABLE1', 'TABLE2' ) ;

no rows selected