oracle(43)_PL/SQL_触发器

PL/SQL

触发器

触发器
  • 数据库触发器是一个与表相关联的、存储的 PL/SQL 程序。每当一个特定的数据操作语句(Insert,update,delete) 在指定的表上发出时,Oracle 自动地执行触发器中定义的语句序列。

● 触发器可用于

  • 数据确认
  • 实施复杂的安全性检查
  • 做审计,跟踪表上所做的数据操作等
  • 数据的备份和同步

● 触发器的类型

  • 语句级触发器 :在指定的操作语句操作之前或之后执行一次,不管这条语句影响了多少行 。
  • 行级触发器(FOR EACH ROW) :触发语句作用的每一条记录都被触发。在行级触发器中使用 old 和 new 伪记录变量, 识别值的状态。

● 语法:

CREATE [or REPLACE] TRIGGER 触发器名
   {BEFORE | AFTER}
   {DELETE | INSERT | UPDATE [OF 列名]}
   ON 表名
   [FOR EACH ROW [WHEN(条件) ] ]
begin
   PLSQL 块 
End 触发器名

范例:插入员工后打印一句话 “魏宇轩:一条记录被插入”

  • 示例图:
    oracle(43)_PL/SQL_触发器
    oracle(43)_PL/SQL_触发器
    oracle(43)_PL/SQL_触发器

范例:不能在休息时间插入记录

  • 示例图:
    oracle(43)_PL/SQL_触发器
    oracle(43)_PL/SQL_触发器

● 在触发器中触发语句与伪记录变量的值
oracle(43)_PL/SQL_触发器
范例:判断员工涨工资之后的工资的值一定要大于涨工资之前的工资

  • 示例图:
    oracle(43)_PL/SQL_触发器
    oracle(43)_PL/SQL_触发器

● 以上操作完整源码:

--创建触发器
create or replace trigger insertptrg
  before insert on person
begin
  dbms_output.put_line('魏宇轩:一条记录被插入');
end insertptrg;
--测试
insert into person
  (person_id, pname, age, birthday, address)
values
  (003, 'Kang', 20, to_date('1998-10-25', 'yyyy-mm-dd'), 'ChangSha'); 
--查看是否插入成功
select * from person;

---------------------------------------------------------------------------
--创建触发器
create or replace trigger valid_insert_p
  before insert on person
declare
  cruday varchar2(10);--定义字符串的时候要给长度
begin
  select to_char(sysdate, 'day') into cruday from dual;
  if cruday in ('星期六') then
    raise_application_error(-20001, '星期六不允许插入数据');
  end if;
end valid_insert_p;
--测试
insert into person
  (person_id, pname, age, birthday, address)
values
  (004, 'KK', 20, to_date('1998-10-25', 'yyyy-mm-dd'), 'KunMing'); 
--查看是否插入成功
select * from person;  

---------------------------------------------------------------------------
----创建触发器
create or replace trigger vaild_addsal
  before update of sal on myemp
  for each row
begin
  if :new.sal <= :old.sal then
    raise_application_error(-20002, '涨后的工资不能比涨前的低');
  end if;
end valid_addsal;
--测试
update myemp t set t.sal = t.sal + 100 where t.empno = 7369;
update myemp t set t.sal = t.sal - 100 where t.empno = 7369;

如有错误,欢饮指正!