3

我正在执行一个类似的语句

DELETE FROM USER WHERE USER_ID=1;

在 SQL 开发人员中。

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

有什么办法可以找出来。通过 SQL 语句,直接在 sqldeveloper 中的日志文件或任何其他想法?

4

1 回答 1

3

虽然这对于 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
于 2013-01-21T13:46:50.143 回答