首页 > 代码库 > 触发器运用示例---laobai

触发器运用示例---laobai

--1 禁止将emp的用户名修改为含有sb关键字
--创建emp表的update行前触发器
create or replace trigger emp_update_ename_tri
before update on scott.emp for each row
declare  
begin
  if (instr(upper(:new.ename),‘SB‘)>0) then
    raise_application_error(-20001,‘禁止将emp表的用户名修改为含SB‘);
   end if;
   dbms_output.put_line(‘修改emp成功!‘||sysdate);
end;

--测试触发器
update scott.emp set ename=‘SSSA‘ where empno=‘7369‘


--2 备份表的测试
 --删除scott.emp表时,可以自动备份表插入被删除的记录
 --创建备份表
 create table emp_bk as (select * from scott.emp)
 truncate table emp_bk
 --
 select * from emp_bk;
 
 --创建scott.emp的delete行前触发器
 
 create or replace trigger emp_delete_bk_tri 
 before delete on scott.emp for each row
 declare 
 begin
   dbms_output.put_line(‘开始备份...‘);
   insert into emp_bk values(:old.empno,:old.ename,:old.job,
   :old.mgr,:old.hiredate,:old.sal,:old.comm,:old.deptno);
   dbms_output.put_line(‘完成备份...‘);
 end;
 
delete from scott.emp  where empno=‘7369‘
delete from scott.emp  where ename like ‘%黑%‘
 
select * from scott.emp 

--3  免主键的自增

create table person
(
  pid number primary key ,
  pname varchar2(20) not null    
)
select * from person;
create sequence person_se

truncate table person;

insert into person values(person_se.nextval,‘白‘||person_se.currval);
insert into person (pname) values(‘白100‘);

--创建insert行前触发器,可以省略主键的自增
create or replace trigger person_inser_tri
before insert on person for each row
declare
v_no number;
v_count number;
begin
   if(:new.pid is null)   then
   loop
    select person_se.nextval into v_no  from dual;
    select count(1) into v_count from person where pid=v_no;
    if(v_count=0) then  --此次生成的新序号不存在的,是有效的
      :new.pid := v_no;
      exit;
    end if;
     end loop;
    end if;
 end;
 
 insert into person (pid,pname) values(‘38‘,‘白100‘);

  

触发器运用示例---laobai