• 触发器


    应用场景:

    1.复杂的安全性的场景(涉及到权限的问题);
    例子:下班时间不能插入数据库;
    2.数据的确认(涉及数据是否合理问题);
    例子:涨工资越涨越高,低了就不能修改;
    3.数据的审计(涉及到数据的增、删、改的操作记录)---Oracle自身已经实现了审计;
    例子:把操作的时间、帐户等信息记录下来;4.数据的备份和同步(备份和同步重要);
    例子:不同的数据表间进行同步备份

    什么是触发器:

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

    触发器:

    1.创建触发器的语法

      create or replace trigger 触发器名称
      before (after)
      delete (insert update) [of 列名] --of 列名表示该列发生变化时,触发该触发器
      on 表名
      [for each row[when条件]] --行级触发器的关键字
      PLSQL块

    2.触发器的两种类型

    语句级触发器:不管这条语句影响多少行,只执行一次(针对表)
      行级触发器:每影响一行,都被触发一次。
    行级触发器中使用:old :new伪记录变量(针对行)第一个触发器:每当成功插入新员工后,自动打印“成功插入新员工”触发器单词:trigger
    create trigger saynewem //创建触发器名称
    after insert //在插入操作以后
    on emp //针对emp的表
    declare //操作体
    begin
    //触发器操作的内容 
    end;
    

    触发器案例一 : 复杂的安全性检查

    例如禁止在非工作时间插入数据
    /**
      1.周末: to_char(sysdate,'day') in ('星期六',‘星期日’)
      2.上班前,下班后: to_number(to_char(sysdate,'hh24')) not between 9 and 18
    /
    
    --例如禁止在非工作时间插入数据
    /**
      1.周末: to_char(sysdate,'day') in ('星期六',‘星期日’)
      2.上班前,下班后: 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;
    

    触发器案例二: 数据的确认

    涨工资不能越涨越少
    :old 表示操作该行之前这一行的值
    :new 表示操作该行之后这一行的值
    create or replace trigger check_salary
    before update 
    on emp
    for each row
    begin 
    if :new.sal<:odl.sal then
    raise_application_error(-20002,'涨后薪水不能少于涨前薪水。 涨后薪水为:'||:new.sal ||'涨前的薪水:'||:old.sal);
    end if;
    end;
    

    触发器案例三:基于值的审计

    例子:给员工涨工资,当涨后的薪水超过6000块时候,审计该员工的信息
    --创建表,用于保存审计信息
    create table audit_info(
    information varchar2(200)
    );
    create or replace trigger do_audit_emp_salary
    after update 
    on emp
    for each row 
    begin 
    if :new.sal>6000 then 
    insert into audit_info values(:new.empno||' '||:new.ename||' '||:new.sal);
    end if;
    end;
    

      

    触发器应用场景四: 数据的备份和同步

    例子:当给员工涨完工资后,自动备份新的工资资料到备份表中
    

     

    create or replace trigger trigger_sync_salary
    after update 
    on emp
    for each row 
    begin
    update emp_back set sal=:new.sal where empno=:new.empbo;
    end;

     

      

      

  • 相关阅读:
    mysql 索引失效的几种情况
    MYSQL行转列-动态修改
    有A B C三列,用SQL语句实现:当A列大于B列时选择A列否则选择B列
    C++ 的关键字(保留字)完整介绍
    element-ui组件el-upload自定义上传时界面抖动
    React Hooks 组件卸载时触发的方法
    JS中的事件冒泡和事件捕获
    关于tranform: translate 后,元素被覆盖的问题
    Spring Boot使用@Scheduled时需要注意的坑
    redis的Lua脚本事务注意
  • 原文地址:https://www.cnblogs.com/tanlei-sxs/p/9811358.html
Copyright © 2020-2023  润新知