DB2 级联删除命令? [英] DB2 cascade delete command?

查看:32
本文介绍了DB2 级联删除命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种特殊的语法可以在 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 子句创建 FK,要么 使用 subselect-delete 预删除其他行.

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 隔离级别,则可能必须使用 临时表 :

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆