SQL DB2级联删除命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1164296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DB2 cascade delete command?
提问by OverLex
Is there a special syntax to execute a cascade delete on DB2 or is it only possible to create "cascadable" tables by defining them with the "ON DELETE CASCADE" option?
是否有一种特殊的语法可以在 DB2 上执行级联删除,或者是否只能通过使用“ON DELETE CASCADE”选项定义它们来创建“可级联”表?
What I am trying to achieve is delete other table rows based on a same foreign key when I delete that key, but this is done on an already existing and data-filled database.
我想要实现的是在删除该键时删除基于相同外键的其他表行,但这是在已经存在且数据填充的数据库上完成的。
回答by Steve Schnepp
As you stated, you either have to create FKs with an ON DELETE CASCADE
clause or to pre-delete the other rowswith a subselect-delete.
正如您所说,您必须使用ON DELETE CASCADE
子句创建 FK,或者使用 subselect-delete预先删除其他行。
So, if you don't have an ON DELETE CASCADE
clause you have to do
所以,如果你没有一个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';
It is simple, but is somewhat redundant so you may use the WITHstatement.
它很简单,但有些多余,因此您可以使用WITH语句。
If the request to select the required rows is quite big, and if you don't haveat least a RR isolation level, you may have to use a TEMPORARY table:
如果选择所需行的请求非常大,并且您没有至少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
);
This way you are sure that you will delete the same rows in each table, and a FK error will still fire up if you miss something. Per default, the temporary table will empty itself on commit.
这样你就可以确定你会删除每个表中相同的行,如果你遗漏了什么,仍然会触发 FK 错误。默认情况下,临时表将在提交时清空自身。