DB2级联删除命令? [英] DB2 cascade delete command?
问题描述
在DB2上执行级联删除是否有特殊的语法,还是只能通过使用ON DELETE CASCADE选项来创建可级联表来创建级联表?
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?
我想要实现的是在删除该密钥时,基于相同的外键删除其他表行,但是这已经在已经存在和数据填充的数据库上完成。
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.
推荐答案
正如您所说,您必须创建具有 ON DELETE CASCADE
子句,或使用子选择删除预先删除其他行。
As you stated, you either have to create FKs with an ON DELETE CASCADE
clause or to pre-delete the other rows with a subselect-delete.
所以,如果你没有一个 ON DELETE CASCADE
子句你必须做
So, if you don't have an ON DELETE CASCADE
clause you have to do
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 语句。
It is simple, but is somewhat redundant so you may use the WITH statement.
如果选择所需行的请求相当大,而如果您没有至少有一个 RR隔离级别,您可能需要使用 TEMPORARY表 :
If the request to select the required rows is quite big, and if you don't have at least a RR isolation level, you may have to use a TEMPORARY table :
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错误仍然会启动。默认情况下,临时表将在提交时自动清空。
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.
这篇关于DB2级联删除命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!