是否有一种特殊的语法在DB2上执行级联删除,或者只能通过使用“ON DELETE CASCADE”选项定义它们来创建“可级联”表?
我想要实现的是在删除该密钥时删除基于相同外键的其他表行,但这是在已存在且数据填充的数据库上完成的。
答案 0 :(得分:8)
如您所述,您必须使用ON DELETE CASCADE
子句创建FK,或使用subselect-delete 预先删除其他行。< / p>
因此,如果您没有ON DELETE CASCADE
条款,则必须执行
DELETE FROM ORDERS_ITEMS WHERE ORDER_ID in (
SELECT ORDER_ID FROM ORDERS WHERE STATUS = 'Canceled'
);
DELETE FROM ORDERS_ADDRESS WHERE ORDER_ID in (
SELECT ORDER_ID FROM ORDERS WHERE STATUS = 'Canceled'
);
DELETE FROM ORDERS WHERE STATUS = 'Canceled';
这很简单,但有些多余,因此您可以使用WITH语句。
如果选择所需行的请求非常大,而如果您没有至少 RR隔离级别,则可能必须使用{ {3}}:
DECLARE GLOBAL TEMPORARY TABLE TMP_IDS_TO_DELETE (ID BIGINT) NOT LOGGED;
INSERT INTO SESSION.TMP_IDS_TO_DELETE (ID)
SELECT ORDER_ID FROM ORDERS WHERE STATUS = 'Canceled';
DELETE FROM ORDERS_ITEMS WHERE ORDER_ID in (
SELECT ID FROM SESSION.TMP_IDS_TO_DELETE
);
DELETE FROM ORDERS_ADDRESS WHERE ORDER_ID in (
SELECT ID FROM SESSION.TMP_IDS_TO_DELETE
);
DELETE FROM ORDERS WHERE ORDER_ID in (
SELECT ID FROM SESSION.TMP_IDS_TO_DELETE
);
这样您就可以确保删除每个表中的相同行,如果您遗漏了某些内容,FK错误仍然会启动。默认情况下,临时表将在提交时自行清空。