zoukankan      html  css  js  c++  java
  • 触发器运用示例---laobai

    1 触发器
    概念:trigger。逻辑对象的一种。当dml的增删改语句执行时,自动触发一系列动作。
    分类:dml触发器。ddl触发器(很少见)
    sql:ddl,dml,dcl
    按触发的时间分:
    语句执行前-->[行变化之前-->行变化之后]-->语句执行后
    update emp set sal=sal*2; //一共有5条记录。

    按触发的语句分:insert触发,update触发,delete触发。

    对于行触发器:
    :new--执行后的记录
    :old--执行前的记录。delete
    注意:
    a select不能配置触发器。触发器耗费资源,不宜过多。
    b 在触发器内部,可以通过raise_application_error方法来抛出异常,取消原来的修改动作。

    应用:

    a 备份
    b 防止不当的修改数据
    c 省略主键的自增

    案例


    --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');

      

  • 相关阅读:
    Linux 第一个脚本程序
    Linux 8开启FTP功能服务
    PPT 倒计时时钟,用 GIF 动画实现,可直接使用 -- 附 Python 实现代码
    python flask 虚拟环境迁移
    GOLANG学习之路之二
    Golang学习之路之一
    vscode 调试flask项目 解决(socket.gaierror: [Errno 11001] getaddrinfo failed)
    windows下部署 flask (win10+flask+nginx)
    git入门
    配置maven的国内镜像
  • 原文地址:https://www.cnblogs.com/ipetergo/p/6255819.html
Copyright © 2011-2022 走看看