Oracle foreign key cascading delete and cascading update

1 Cascade delete

Oracle has three behaviors: NO ACTION (similar to RESTRICT), CASCADE and SET NULL on the deletion of foreign keys.

The following takes student-class as an example to illustrate the foreign key deletion in different situations. Students belong to the class, and the primary key of the class is the foreign key of the student.

-- class table
CRATE TABLE TB_CLASS
(
  ID NUMBER NOT NULL, --class primary key
  NAME VARCHAR2(50), -- class name
  CONSTRAINT PK_TB_CLASS PRIMARY KEY (ID)
);
 
-- Student table
CREATE TABLE TB_STUDENT
(
  ID NUMBER NOT NULL, --student primary key
  NAME VARCHAR2(50), -- student name
  CLASS_ID NUMBER, -- the class the student belongs to, foreign key
   
  --primary key constraint
  CONSTRAINT PK_TB_STUDENT PRIMARY KEY (ID),
   
  -- foreign key constraints
  --Set cascade delete to NO ACTION
  CONSTRAINT FK_TB_STUDENT_CLASS_ID FOREIGN KEY (CLASS_ID) REFERENCES TB_CLASS (ID)
);
 
-- add class data
INSERT INTO TB_CLASS (ID, NAME) VALUES (1, '一班');
INSERT INTO TB_CLASS (ID, NAME) VALUES (2, '二班');
INSERT INTO TB_CLASS (ID, NAME) VALUES (3, '三班');
 
-- add student data
INSERT INTO TB_STUDENT (ID, NAME, CLASS_ID) VALUES (1, '小明', 1);
INSERT INTO TB_STUDENT (ID, NAME, CLASS_ID) VALUES (2, '小刚', 1);
INSERT INTO TB_STUDENT (ID, NAME, CLASS_ID) VALUES (3, '小王', 1);
INSERT INTO TB_STUDENT (ID, NAME, CLASS_ID) VALUES (4, '二明', 2);
INSERT INTO TB_STUDENT (ID, NAME, CLASS_ID) VALUES (5, '二刚', 2);
INSERT INTO TB_STUDENT (ID, NAME, CLASS_ID) VALUES (6, '二王', 2);
INSERT INTO TB_STUDENT (ID, NAME, CLASS_ID) VALUES (7, '大明', 3);
INSERT INTO TB_STUDENT (ID, NAME, CLASS_ID) VALUES (8, '大刚', 3);
INSERT INTO TB_STUDENT (ID, NAME, CLASS_ID) VALUES (9, '大王', 3);

 initial class data

\"></p> <p>Initial Student Data</p> <p><img style=When the data with hierarchical relationship is stored in the database, the foreign key of the table refers to the primary key of the same table. At this time, cascading updates cannot be implemented with triggers.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326974219&siteId=291194637