• Oracle触发器


    for each row 是针对于行级触发器的,每一行都会执行触发器

    第一个触发器:

    /*
    插入一条记录后,自动打印“成功插入一个员工”
    
    */
    create or replace trigger firstTrigger
    after insert
    on emp
    begin
      dbms_output.put_line('成功插入一个员工');
    end;
    /

    实例一:实施复杂的安全性检查

    /*
    实施复杂的安全性检查
    
    限制非工作时间向数据库插入(emp)数据:
    
    周末: to_char(sysdate,'day') in ('星期六','星期日')
    上班前,下班后:to_number(to_char(sysdate,'hh24')) not between 9 and 18
    */
    create or replace trigger securityEmp
    before insert
    on emp
    begin
    
      if to_char(sysdate,'day') in ('星期六','星期日','星期三') or
         to_number(to_char(sysdate,'hh24')) not between 9 and 18 then
      
        raise_application_error(-20001,'不能在非工作时间插入数据');
         
      end if;     
    end;
    /

    RAISE_APPLICATION_ERROR:在子程序内部使用时,能从存储子程序中抛出自定义的错误消息。这样就能将错误报告给应用程序而避免范围未捕获异常。

    语法如下:error_number是范围在-20000到-20999之间的负整数

    RAISE_APPLICATION_ERROR(error_number, error_message, [keep_errors]);

    实例二:确认数据(行级触发器)
    /*
    确认数据(涨后的薪水不能少于涨前的薪水)
    */
    create or replace trigger checksal
    before update
    on emp
    for each row
    begin
    
      if :new.sal < :old.sal then
        raise_application_error(-20001,'涨后的薪水不能少于涨前的薪水.涨前:'||:old.sal||' 涨后:'||:new.sal);
      end if;
    
    end;
    /
    伪记录变量,代表一行,针对行级触发器

     练习:每个部门最多只能有5名员工

    create or replace trigger empNumLimitTrigger
      before insert on emp2  
      for each row
    declare
      empCount number:=0;
    begin
       select count(*) into empCount from emp2 where deptno=:new.deptno; 
       if empCount+1>5 then 
        raise_application_error(-20001,'每个部门最多只能有五名员工!,添加失败!');
       end if;
    end empNumTrigger;
  • 相关阅读:
    poj2229 Sumsets (递推)
    hihocoder1148 February 29(区间闰年计数)
    sort函数比较cmp写法
    字符串忽略大小写
    地形
    启用和禁用warning
    AppStore SDK
    NGUI List优化
    ETC1
    加载
  • 原文地址:https://www.cnblogs.com/lihaoyang/p/8676882.html
Copyright © 2020-2023  润新知