我有一张桌子,这张桌子最多必须有1000行。当用户想要添加第1001行时,必定存在错误。我知道我应该使用插入触发器。我是SQL的新人你能帮助我吗?
我的代码是:
create or replace trigger update_ext_app_serv
before update on EXTERNAL_APP_SERVICE
for each row
declare
row_count number;
old_service_id number;
new_service_trigger varchar(30);
old_service_trigger varchar(30);
begin
row_count := 0;
new_service_trigger := :NEW.TRIGGER_NAME;
old_service_trigger := :OLD.TRIGGER_NAME;
old_service_id := :OLD.SERVICE_ID;
select count(*) into row_count
from EXTERNAL_APP_PROFILE
where ORIG_ID = old_service_id
or TERM_FAILURE_RESP_ID = old_service_id
or TERM_ID = old_service_id;
if (row_count > 0) and (new_service_trigger not like old_service_trigger)
then
raise_application_error(-20706, 'Unable to update Trigger. The service is referenced at least External Application Profile.');
end if;
end;
答案 0 :(得分:1)
执行此操作的方法是使用AFTER触发器,并在语句而不是行级别。
SQL> create or replace trigger t1000_trg
2 after insert on t1000
3 declare
4 n pls_integer;
5 begin
6 select count(*) into n
7 from t1000;
8 if n > 1000 then
9 raise_application_error(-20999, 'No more than 1000 records!');
10 end if;
11 end;
12 /
Trigger created.
SQL>
这是我们的测试数据。
SQL> select count(*) from t1000;
COUNT(*)
----------
999
SQL>
第1000条记录好......
SQL> insert into t1000 values (1000);
1 row created.
SQL>
...但是第1001条记录被拒绝了:
SQL> insert into t1000 values (1001);
insert into t1000 values (1001)
*
ERROR at line 1:
ORA-20999: No more than 1000 records!
ORA-06512: at "FOX.T1000_TRG", line 7
ORA-04088: error during execution of trigger 'FOX.T1000_TRG'
SQL>
也适用于多行插入语句。
SQL> roll
Rollback complete.
SQL> select count(*) from t1000;
COUNT(*)
----------
999
SQL> insert into t1000 select 1000 + level from dual connect by level <= 5;
insert into t1000 select 1000 + level from dual connect by level <= 5
*
ERROR at line 1:
ORA-20999: No more than 1000 records!
ORA-06512: at "FOX.T1000_TRG", line 7
ORA-04088: error during execution of trigger 'FOX.T1000_TRG'
SQL>