• 触发器


    定义

    是指一段代码,当触发某个事件的时候,自动执行该段代码。

    应用场景

      1.数据库中相关表实现级联
      2.实时监控某张表的字段数据改变,然后对应执行某些操作
      3.自动生成某些业务编号

    触发器主要有

      【After|before】【insert|update|delete】

    1.触发器查看

    show triggers或者show triggers from user_db;
    通过information_schema.triggers表查看触发器:
    select * from information_schema.triggers;

    2.删除trigger

    drop trigger if exists trigger_name

    3.完整的测试

    drop table if exists tmp1;
    drop table if exists tmp2;
    create table tmp1 (id int, name varchar(128)) default charset='utf8';
    create table tmp2 (fid int, name varchar(128)) default charset='utf8';
    insert into tmp1 values(1, '爱E族');
    insert into tmp2 values(1, '爱E族');
    创建触发器
    DELIMITER $
    drop trigger if exists tmp1_update$
    create trigger tmp1_update after update on tmp1
    for each row
    begin
    update tmp2 set name=new.name where fid=new.id;
    end$
    DELIMITER ;
    创建触发器
    DELIMITER $
    drop trigger if exists tmp1_insert$
    create trigger tmp1_insert before insert on tmp1
    for each row
    begin
    set new.n2 = new.n1*5;
    end$
    DELIMITER ;
    更新操作与if结合
    if old.type=1 then
    update table ...;
    elseif old.type=2 then
    update table ...;
    end if;
    CREATE trigger updatetbl_slope
    AFTER update on tbl_slope for each row
    BEGIN
    if EXISTS(SELECT * FROM user A WHERE A.ID=new.UNIFIEDCODE LIMIT 1)
    THEN
    update user set LastTime=NOW() where ID=NEW.UNIFIEDCODE;
    else
    insert into checkupdates VALUES(new.UNIFIEDCODE, ‘TBL_AVALANCHE’, NOW());
    END if;
    END
    注意
    在使用触发器的时候,我们常常会考虑到,是否可一在触发创建的时候先检查是否有该数据,如果没有就创建。反之则更新数据。
    这个在触发器中也是可以实现的,如:AFTER update|create on tbl_slope for each row。但是这样会是得模糊了触发器的真实实现,
    我个人觉得还是拆开更简洁,更易于维护。
    触发器Before和After的区别。
          (1) before(insert、update)可以对new进行修改;
          (2) after不能对new进行修改;
          (3) 两者都不能修改old数据;
          (4) 对于Insert语句,只有new是合法的,对于delete语句,只有old合法,而update可以在new和old同时使用。
          否则,在after insert触发器中使用old,报错如下:
          [Err] 1363 - There is no OLD row in on INSERT trigger
    :NEW 和:OLD使用方法和意义,new 只出现在insert和update时,old只出现在update和delete时。在insert时new表示新插入的行数据,
        update时new表示要替换的新数据、old表示要被更改的原来的数据行,delete时old表示要被删除的数据。
        不管是after ,还是 before  在update , insert , delete 时,一定是在事务提交之后才会触发触发器
      
  • 相关阅读:
    过滤textarea
    vue引用jquery
    vue_ajax插件Axios
    VeeValidate
    mongodb
    WEBGL实现--three.js笔记整理
    My SQLworkbench问题总结
    vue遇到的问题
    MYSQL使用笔记
    vue笔记
  • 原文地址:https://www.cnblogs.com/topass123/p/16523203.html
Copyright © 2020-2023  润新知