Truncate table in Oracle getting errors

后端 未结 9 1264
忘了有多久
忘了有多久 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-02 08:53

    Issue:

    Error “ORA-02266: unique/primary keys in table referenced by enabled foreign keys” when trying to truncate a table.
    

    Error Message:

    SQL> truncate table TABLE_NAME;  
    
    truncate table TABLE_NAME
               *
    ERROR at line 1:
    ORA-02266: unique/primary keys in table referenced by enabled foreign keys
    

    Solution: -- Find the referenced foreign key constraints.

     SQL> select 'alter table '||a.owner||'.'||a.table_name||' disable constraint '||a.constraint_name||';'
      2  from all_constraints a, all_constraints b
      3  where a.constraint_type = 'R'
      4  and a.r_constraint_name = b.constraint_name
      5  and a.r_owner  = b.owner
      6  and b.table_name = 'TABLE_NAME';
    
        'ALTER TABLE'||A.OWNER||'.'||A.TABLE_NAME||'DISABLE CONSTRAINT'||A.CONSTRAINT_NAME||';'
        ---------------------------------------------------------------------------------------------------------
        alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT disable constraint CONSTRAINT_NAME;    
    alter table SCHEMA_NAME.TABLE_NAME_LOCATION disable constraint CONSTRAINT_NAME;
    

    -- Disable them

    alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT disable constraint CONSTRAINT_NAME;
    alter table SCHEMA_NAME.TABLE_NAME_LOCATION disable constraint CONSTRAINT_NAME;
    

    -- Run the truncate

    SQL> truncate table TABLE_NAME;
    
    Table truncated.
    

    -- Enable the foreign keys back

     SQL> select 'alter table '||a.owner||'.'||a.table_name||' enable constraint '||a.constraint_name||';'
      2  from all_constraints a, all_constraints b
      3  where a.constraint_type = 'R'
      4  and a.r_constraint_name = b.constraint_name
      5  and a.r_owner  = b.owner
      6  and b.table_name = 'TABLE_NAME';
    
    'ALTER TABLE'||A.OWNER||'.'||A.TABLE_NAME||'ENABLE CONSTRAINT'||A.CONSTRAINT_NAME||';'
    --------------------------------------------------------------------------------
    
    alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT enable constraint CONSTRAINT_NAME;
    alter table SCHEMA_NAME.TABLE_NAME_LOCATION enable constraint CONSTRAINT_NAME;
    

    -- Enable them

    alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT enable constraint CONSTRAINT_NAME;
    alter table SCHEMA_NAME.TABLE_NAME_LOCATION enable constraint CONSTRAINT_NAME;
    

提交回复
热议问题