父 table 上的 TRUNCATE 导致删除外键值为 NULL 的子 table 记录
TRUNCATE on a parent table causes deletion of a child table records with NULL value for foreign key
为什么在父 table 上使用带有 CASCADE 子句的 TRUNCATE 时,子 table 中的所有行都被删除,即使子 table 中的某些记录具有 NULL 值外键。
据我了解,为外键设置 NULL 值不应该 link 给定行中的数据到父 table。
在 Oracle 12c 和 18 (Live SQL) 中测试的语句如下:
CREATE TABLE ports
(
port_id NUMBER,
port_name VARCHAR2(20) CONSTRAINT port_description_nn NOT NULL ENABLE,
country VARCHAR2(40),
capacity NUMBER,
CONSTRAINT port_pk PRIMARY KEY (port_id)
);
CREATE TABLE ships
(
ship_id NUMBER PRIMARY KEY,
ship_name VARCHAR2(20),
home_port_id NUMBER,
CONSTRAINT ships_ports_fk FOREIGN KEY (home_port_id) REFERENCES ports (
port_id) ON DELETE CASCADE
);
INSERT INTO ports
VALUES (315,
'ATLANTA',
'USA',
100000);
INSERT INTO ships
VALUES (4000,
'CODD LAND ROVER',
315);
INSERT INTO ships
VALUES (4001,
'CODD VESSEL TWO',
NULL);
在此之后,下面的语句
TRUNCATE TABLE PORTS CASCADE;
删除 SHIPS table 中的所有行,即使 'Codd Vessel Two' 对于 HOME_PORT_ID 具有 NULL 值,这是一个外键。
这是预期的结果吗,因为创建外键时有 ON DELETE CASCADE 子句?
Is this an expected result?
是的。 TRUNCATE 命令的文档说:
CASCADE
If you specify CASCADE, then Oracle Database truncates all child
tables that reference table with an enabled ON DELETE CASCADE
referential constraint. This is a recursive operation that will
truncate all child tables, granchild tables, and so on, using the
specified options.
为什么在父 table 上使用带有 CASCADE 子句的 TRUNCATE 时,子 table 中的所有行都被删除,即使子 table 中的某些记录具有 NULL 值外键。
据我了解,为外键设置 NULL 值不应该 link 给定行中的数据到父 table。
在 Oracle 12c 和 18 (Live SQL) 中测试的语句如下:
CREATE TABLE ports
(
port_id NUMBER,
port_name VARCHAR2(20) CONSTRAINT port_description_nn NOT NULL ENABLE,
country VARCHAR2(40),
capacity NUMBER,
CONSTRAINT port_pk PRIMARY KEY (port_id)
);
CREATE TABLE ships
(
ship_id NUMBER PRIMARY KEY,
ship_name VARCHAR2(20),
home_port_id NUMBER,
CONSTRAINT ships_ports_fk FOREIGN KEY (home_port_id) REFERENCES ports (
port_id) ON DELETE CASCADE
);
INSERT INTO ports
VALUES (315,
'ATLANTA',
'USA',
100000);
INSERT INTO ships
VALUES (4000,
'CODD LAND ROVER',
315);
INSERT INTO ships
VALUES (4001,
'CODD VESSEL TWO',
NULL);
在此之后,下面的语句
TRUNCATE TABLE PORTS CASCADE;
删除 SHIPS table 中的所有行,即使 'Codd Vessel Two' 对于 HOME_PORT_ID 具有 NULL 值,这是一个外键。
这是预期的结果吗,因为创建外键时有 ON DELETE CASCADE 子句?
Is this an expected result?
是的。 TRUNCATE 命令的文档说:
CASCADE
If you specify CASCADE, then Oracle Database truncates all child tables that reference table with an enabled ON DELETE CASCADE referential constraint. This is a recursive operation that will truncate all child tables, granchild tables, and so on, using the specified options.