| Oracle FAQ | Your Portal to the Oracle Knowledge Grid | |
Home -> Community -> Usenet -> comp.databases.theory -> Re: Help with cascading deletion in foreign keys
CREATE TABLE Students
(stu_id INTEGER NOT NULL PRIMARY KEY);
CREATE TABLE Classes
(class_id INTEGER NOT NULL PRIMARY KEY);
CREATE TABLE Registration
(stu_id INTEGER NOT NULL,
REFERENCES Students (stu_id)
ON UPDATE CASCADE
ON DELETE CASCADE,
class_id INTEGER NOT NULL
REFERENCES Classes
ON UPDATE CASCADE
ON DELETE CASCADE,
PRIMARY KEY (stu_id, class_id));
How it should function:
DELETE FROM Student
WHERE NOT EXISTS
(SELECT *
FROM Registration AS R1
R1.stu_id = Student.stu_id);
7) If a class is removed all the rows in Registration are removed from that class. And all Students who were only in that class are deleted but Students that are still in other Classes are not deleted.
DELETE FROM Classes
WHERE NOT EXISTS
(SELECT *
FROM Registration AS R1
WHERE R1.class_id = Classes.class_id);
Okay, we could put these DELETEs in triggers or even a CREATE ASSERTION statement. But try this nightmare:
CREATE TABLE Students
(stu_id INTEGER NOT NULL PRIMARY KEY,
stu_id_1 INTEGER NOT NULL UNIQUE
REFERENCES Registration (stu_id)
ON DELETE CASCADE,
CHECK (stu_id = stu_id_1));
CREATE TABLE Classes
(class_id INTEGER NOT NULL PRIMARY KEY,
class_id_1 INTEGER NOT NULL UNIQUE
REFERENCES Registration (class_id)
ON DELETE CASCADE,
CHECK (class_id = class_id_1)
);
CREATE TABLE Registration
(stu_id INTEGER NOT NULL UNIQUE
REFERENCES Students (stu_id)
ON DELETE CASCADE,
class_id INTEGER NOT NULL UNIQUE
REFERENCES Classes
ON DELETE CASCADE,
PRIMARY KEY (stu_id, class_id));
This passes the Mimer validation, but you'd better defer constraints so you can insert data into the tables. Received on Wed Feb 11 2004 - 12:09:04 CST
![]() |
![]() |