Useful shortcuts for vi editor

Showing posts with label constraint. Show all posts
Showing posts with label constraint. Show all posts

Wednesday, 25 April 2018

ORA-02292 solution

Preparation
-- Insert test data into DEPARTMENT and EMPLOYEES tables.
SQL>
INSERT INTO DEPARTMENTS
VALUES (280,'New Department',100,1700);

SQL>
INSERT INTO EMPLOYEES
VALUES (207,'John','Mathew','JMATHEW','111.111.111',TO_DATE('25.04.2018','DD.MM.YYYY'),'IT_PROG',10000,0.5,100,280);

SQL>
INSERT INTO EMPLOYEES
VALUES (208,'Jim','Parker','JPARKER','111.111.111',TO_DATE('25.05.2018','DD.MM.YYYY'),'IT_PROG',20000,0.6,100,280);

SQL>
INSERT INTO EMPLOYEES
VALUES (209,'Sophia','Ran','SRAN','111.111.111',TO_DATE('25.06.2018','DD.MM.YYYY'),'IT_PROG',30000,0.7,100,280);

SQL>
INSERT INTO EMPLOYEES
VALUES (210,'Wendi','Blake','WBLAKE','111.111.111',TO_DATE('25.07.2018','DD.MM.YYYY'),'IT_PROG',40000,0.8,100,280);

SQL>
COMMIT;

Action
SQL>
DELETE FROM DEPARTMENTS
WHERE DEPARTMENT_ID = 280;

Error
ORA-02292: integrity constraint (HR.EMP_DEPT_FK) violated - child record found

Solution
-- Find referencial integrity constraint between DEPARTMENT and EMPLOYEES tables for this error.
SQL>
SELECT * 
FROM ALL_CONSTRAINTS 
WHERE TABLE_NAME IN ('EMPLOYEES', 'DEPARTMENTS') AND CONSTRAINT_TYPE = 'R';

-- Drop constraint
SQL>
ALTER TABLE EMPLOYEES DROP CONSTRAINT EMP_DEPT_FK;

-- Re-define constraint with "ON DELETE CASCADE" option
SQL>
ALTER TABLE EMPLOYEES
ADD CONSTRAINT EMP_DEPT_FK 
FOREIGN KEY (DEPARTMENT_ID)
REFERENCES DEPARTMENTS(DEPARTMENT_ID)
ON DELETE CASCADE;

-- Try again
SQL>
DELETE FROM DEPARTMENTS
WHERE DEPARTMENT_ID = 280;

SQL>
COMMIT;