Search code examples
sqloracleforeign-keys

enable oracle SQL constraints


someone who can help me, disable the constraint of a table in the database using cascade, the problem I have now is that I don't know how I can enable everything using cascade or how I can validate that everything is enabled again


Solution

  • There's no cascade enable foreign key constraints, if that's what you are asking - you'll have to do it manually. It's not that complicated; have a look at the following example.

    There are some foreign key constraints in my schema that are disabled:

    SQL> select table_name, constraint_name, status
      2  from user_constraints where constraint_type = 'R';
    
    TABLE_NAME                     CONSTRAINT_NAME                STATUS
    ------------------------------ ------------------------------ --------
    EMP                            FK_EMP_DEPT                    DISABLED
    BONUS                          FK_BON_EMP                     DISABLED
    

    The following script searches for such a constraints (in USER_CONSTRAINTS) and enables them in a loop, using dynamic SQL (as you can't perform DDL in PL/SQL otherwise):

    SQL> declare
      2    l_str varchar2(400);
      3  begin
      4    for cur_r in (select table_name, constraint_name
      5                  from user_constraints
      6                  where constraint_type = 'R' and status = 'DISABLED'
      7                 )
      8    loop
      9      l_str := 'alter table ' || cur_r.table_name ||
     10               '  enable constraint ' || cur_r.constraint_name;
     11      dbms_output.put_line(l_str);
     12      execute immediate l_str;
     13    end loop;
     14  end;
     15  /
    alter table EMP  enable constraint FK_EMP_DEPT
    alter table BONUS  enable constraint FK_BON_EMP
    
    PL/SQL procedure successfully completed.
    

    The result: they are enabled:

    SQL> select table_name, constraint_name, status
      2  from user_constraints where constraint_type = 'R';
    
    TABLE_NAME                     CONSTRAINT_NAME                STATUS
    ------------------------------ ------------------------------ --------
    EMP                            FK_EMP_DEPT                    ENABLED
    BONUS                          FK_BON_EMP                     ENABLED
    
    SQL>