如何使用触发器调用过程

How to call procedure using triggers

Table:

create table department(deptno number, deptname varchar2(50), deptloc varchar2(50));

insert into department values(1,'A','X');
insert into department values(2,'B','Y');
insert into department values(3,'C','Z');

存储过程:

create or replace procedure secure_dml(i_month IN varchar2)
is

begin
if i_month <> 'March' then
dbms_output.put_line('You can modify or add a department only at the end of a financial year');
else 
--should I write insert/update DML statement?

end;

触发器:

create or replace trigger tr_check_dept before insert on department
begin
dbms_output.put_line('Record inserted');
end;

要求:

借助过程和触发器实现以下业务规则:-

基本上,您可以在一个触发器内完成所有操作,但没关系 - 这是某种家庭作业。这是我的理解。

程序没有做任何“聪明”的事情,只是显示消息。请注意 DBMS_OUTPUT.PUT_LINE 调用会显示一条消息,它不会阻止任何人做任何事情 - 而不是它,您应该 raise_application_error.

您问题的答案

should I write insert/update DML statement?

是 - 在我看来 - ,你不应该。


触发器调用该过程。你的不检查月份,而它应该检查(即将该控件从过程移至触发器)。


所有东西放在一起可能看起来像这样:

SQL> create or replace procedure secure_dml
  2  is
  3  begin
  4    raise_application_error(-20000,
  5      'You can modify or add a department only at the end of a financial year');
  6  end;
  7  /

Procedure created.

SQL> create or replace trigger tr_check_dept
  2    before insert on department
  3    for each row
  4  begin
  5    if extract(month from sysdate) <> 3 then
  6       secure_dml;
  7    end if;
  8  end;
  9  /

Trigger created.

SQL> insert into department(deptno, deptname, deptloc)
  2    values (4, 'D', 'W');
insert into department(deptno, deptname, deptloc)
            *
ERROR at line 1:
ORA-20000: You can modify or add a department only at the end of a financial year
ORA-06512: at "SCOTT.SECURE_DML", line 4
ORA-06512: at "SCOTT.TR_CHECK_DEPT", line 3
ORA-04088: error during execution of trigger 'SCOTT.TR_CHECK_DEPT'


SQL>

仅出于测试目的,因为今天是 9 月,让我们修改触发器代码,使其适用于本月(而不是 3 月),看看 INSERT 在这种情况下会做什么。

SQL> create or replace trigger tr_check_dept
  2    before insert on department
  3    for each row
  4  begin
  5    if extract(month from sysdate) <> 9 then      --> this line was changed
  6       secure_dml;
  7    end if;
  8  end;
  9  /

Trigger created.

SQL> insert into department(deptno, deptname, deptloc)
  2    values (4, 'D', 'W');

1 row created.

SQL>

对;现在可以了。