clicksor ad

Thursday, July 08, 2010

Deleting child records and parent records

How  to delete all corresponding child records in order to
delete the parent record.

 example:
CREATE TABLE EMP (
ENO NUMBER(3) NOT NULL,
NAME VARCHAR2(5),
DNO NUMBER(2) NOT NULL,
CONSTRAINT EMP_FKEY FOREIGN KEY (DNO)
REFERENCES DEPT (DNO) INITIALLY IMMEDIATE DEFERRABLE,
CONSTRAINT EMP_PKEY PRIMARY KEY (ENO));


SQL> set constraint emp_fkey deferred;        The order of deletes is now not important
SQL> delete dept where dno=20;
SQL> delete emp where dno=20;                    Constraints are checked only now
SQL> commit;                                                Put the constraint back to its original state
SQL> set constraint emp_fkey immediate;

"delete cascade" with the FK constraint definition will also do but not advisable
ensure that the FK columns on the child tables are indexed.

No comments: