如果我是你,我会创建一个外键约束并让数据库处理它。像这样的:
样本数据:
SQL> select * from test_categories;
ID NAME VISIBLE
---------- ----------- ----------
1 furniture 1
2 consumables 1
3 delete me 1 --> not referenced from TEST_ENTRIES table
SQL> select * from test_entries;
ID NAME CAT_ID
---------- -------- ----------
1 desk 1
2 armchair 1
3 other 2
给TEST_CATEGORIES添加一个主键(否则外键不能引用):
SQL> alter table test_categories add constraint pk_cat
2 primary key (id);
Table altered.
向 TEST_ENTRIES 添加外键:
SQL> alter table test_entries add constraint fk_ent_cat
2 foreign key (cat_id)
3 references test_categories (id);
Table altered.
测试:ID = 1 引用自 TEST_ENTRIES,因此 Oracle 不会让您删除它:
SQL> delete from test_categories where id = 1;
delete from test_categories where id = 1
*
ERROR at line 1:
ORA-02292: integrity constraint (SCOTT.FK_ENT_CAT) violated - child record
found
但是,ID = 3 没有被引用,将被成功删除:
SQL> delete from test_categories where id = 3;
1 row deleted.
SQL>
如果您想创建自己的代码,方法如下;我在 SQL*Plus 中运行它,所以我使用替换变量&&P1_CAT_ID。取而代之的是:P1_CAT_ID(即页面项目)并省略第 14 行,因为它在 Apex 中无用。
SQL> rollback;
Rollback complete.
SQL> declare
2 l_cnt number;
3 begin
4 select count(*)
5 into l_cnt
6 from test_entries e
7 where e.cat_id = &&P1_CAT_ID; --> you'd use :P1_CAT_ID
8
9 if l_cnt > 0 then
10 raise_application_error(-20000, 'Not allowed, child records exist');
11 else
12 delete from test_categories
13 where id = &&P1_CAT_ID; --> you'd use :P1_CAT_ID
14 dbms_output.put_line(sql%rowcount ||' row(s) deleted');
15 end if;
16 end;
17 /
Enter value for p1_cat_id: 1
declare
*
ERROR at line 1:
ORA-20000: Not allowed, child records exist
ORA-06512: at line 10
SQL> undefine p1_cat_id
SQL> /
Enter value for p1_cat_id: 3
1 row(s) deleted
PL/SQL procedure successfully completed.
SQL>