Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's quite problematic to achieve what you want, but not impossible.</p> <p>The deal here is that you must deal with any possible constraints before setting the key to null.</p> <p>I believe we need to use a little dynamic SQL here if we want to achieve a solution.</p> <p>Here's the modified version of your trigger I quickly adjusted (Note: I haven't tested it):</p> <pre><code>create or replace trigger UPDATE_EMPLOYEES_DEPT_ID before update or delete of DEPARTMENT_ID on DEPARTMENTS for each row begin if UPDATING then update EMPLOYEES set DEPARTMENT_ID = :new.DEPARTMENT_ID where DEPARTMENT_ID = :OLD.DEPARTMENT_ID; elsif DELETING then for i in ( select CONSTRAINT_NAME from USER_CONSTRAINTS where CONSTRAINT_TYPE='R' and R_CONSTRAINT_NAME in (select CONSTRAINT_NAME from USER_CONSTRAINTS where CONSTRAINT_TYPE in ('P','U') and TABLE_NAME='EMPLOYEES') ) loop for j in ( select TABLE_NAME, COLUMN_NAME from USER_CONS_COLUMNS where CONSTRAINT_NAME = i.CONSTRAINT_NAME ) loop update j.TABLE_NAME set j.COLUMN_NAME = null where j.COLUMN_NAME = :OLD.DEPARTMENT_ID; end loop; end loop; update EMPLOYEES set DEPARTMENT_ID = null where DEPARTMENT_ID = :OLD.DEPARTMENT_ID; end if; end; </code></pre> <p>Let me explain a little how it works regarding the delete:</p> <ul> <li>First it grabs all the foreign keys referencing the table 'EMPLOYEES'</li> <li>Then for each foreign key found it grabs the table name and column it references</li> <li>Then for each table-column pair it nulls the values of those fields which match the :OLD.DEPARTMENT_ID</li> <li>Finally after dealing with all the foreign keys it nulls the DEPARTMENT_ID in the EMPLOYEES table as you had planned initially.</li> </ul> <p>As I haven't really tested this, let me know if this causes any problems.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload