是否有在DB2上执行级联删除的特殊语法,还是只能通过使用“ ON DELETE CASCADE”选项定义它们来创建“可级联”表?
我要实现的目的是在删除键时基于相同的外键删除其他表行,但这是在已存在且已填充数据的数据库上完成的。
如您所述,您要么必须 创建带有ON DELETE CASCADE子句的 FK, 要么要使用subselect-delete来 预删除其他行 。
ON DELETE CASCADE
因此,如果您没有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隔离级别 ,则可能必须使用 TEMPORARY表 :
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错误。默认情况下,临时表将在提交时将自身清空。