gpt4 book ai didi

Oracle删除语句: how many rows have been deleted by cascade delete

转载 作者:行者123 更新时间:2023-12-03 02:45:11 32 4
gpt4 key购买 nike

我正在执行类似的语句

DELETE FROM USER WHERE USER_ID=1;

在 SQLDeveloper 中。

由于用户在许多表中被引用(例如用户有订单、设置等),我们激活了 ON DELETE CASCADE,这样我们就不必手动删除每一行。然而,在开发过程中,我们有兴趣知道级联删除“自动”删除了多少行以及哪些表。

有什么办法可以查到这个吗?通过 SQL 语句、直接在 sqldeveloper 中从日志文件或任何其他想法?

最佳答案

虽然这对于 sql%rowcount 来说是不可能的,但如果您编写触发器代码,这是可能的,但这意味着您需要在要监视的所有表上使用触发器。触发器也会稍微减慢操作速度。

例如:

SQL> select * from one;

ID
----------
1
2

SQL> select * from child_of_one;

ID O_ID
---------- ----------
1 1
2 1
3 1
4 2
5 2
6 2
7 2
8 2

我们想要一个包规范来保存一组表+计数:

SQL> create or replace package foo
2 as
3 type rowcount_tab is table of pls_integer index by varchar2(30);
4 t_rowcount rowcount_tab;
5 end foo;
6 /

Package created.

我们希望顶层表上有一个触发器将这些计数重置为零:

SQL> create or replace trigger one_biud
2 before insert or update or delete
3 on one
4 declare
5 begin
6 foo.t_rowcount.delete;
7 end;
8 /

Trigger created.

这假设您只对从顶级表中删除的数组感兴趣。如果没有,您需要在每个表上使用 foo.t_rowcount.delete('TABLE_NAME') 来代替触发器。

现在在每个感兴趣的表上的每行触发器之后设置数组:

SQL> create or replace trigger one_aiudfer
2 after insert or update or delete
3 on one
4 for each row
5 declare
6 begin
7 if (foo.t_rowcount.exists('ONE'))
8 then
9 foo.t_rowcount('ONE') := nvl(foo.t_rowcount('ONE'), 0)+1;
10 else
11 foo.t_rowcount('ONE') := 1;
12 end if;
13 end;
14 /

Trigger created.

SQL> create or replace trigger child_of_one_aiudfer
2 after insert or update or delete
3 on child_of_one
4 for each row
5 declare
6 begin
7 if (foo.t_rowcount.exists('CHILD_OF_ONE'))
8 then
9 foo.t_rowcount('CHILD_OF_ONE') := nvl(foo.t_rowcount('CHILD_OF_ONE'), 0)+1;
10 else
11 foo.t_rowcount('CHILD_OF_ONE') := 1;
12 end if;
13 end;
14 /

Trigger created.

现在当我们删除或其他什么时:

SQL> delete from one where id = 1;

1 row deleted.

SQL> declare
2 v_table varchar2(30);
3 begin
4 v_table := foo.t_rowcount.first;
5 loop
6 exit when v_table is null;
7 dbms_output.put_line(v_table || ' ' || foo.t_rowcount(v_table) || ' rows');
8 v_table := foo.t_rowcount.next(v_table);
9 end loop;
10 end;
11 /
CHILD_OF_ONE 3 rows
ONE 1 rows

PL/SQL procedure successfully completed.

SQL> delete from one where id = 2;

1 row deleted.

SQL> declare
2 v_table varchar2(30);
3 begin
4 v_table := foo.t_rowcount.first;
5 loop
6 exit when v_table is null;
7 dbms_output.put_line(v_table || ' ' || foo.t_rowcount(v_table) || ' rows');
8 v_table := foo.t_rowcount.next(v_table);
9 end loop;
10 end;
11 /
CHILD_OF_ONE 5 rows
ONE 1 rows

关于Oracle删除语句: how many rows have been deleted by cascade delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14439097/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com