zoukankan      html  css  js  c++  java
  • MySQL数据库----触发器

    触发器-trigger

    触发器:监视某种情况,并触发某种操作。

    使用触发器可以定制用户对表进行【增、删、改】操作时前后的行为,注意:没有查询

    -- 触发器:某种程序触发了工具的运行
    -- 触发器不能主动调用,只有触发了某种行为才会调用触发器的执行
    -- 插入一条记录就触发一次
    -- 还是建议不要用触发器,因为这是BDA管理的,还是不如你在程序里面直接写比较方便

    1.创建触发器的语法

    create
       trigger trigger_name
       trigger_time trigger_event
       on tbl_name for each row
       triggrr_body  #主体,就是在触发器里干什么事
    trigger_time:{before | after}
    trigger_event:{insert | update |detele}

    准备表

    -- # 2.准备表
    -- #第一步:准备表
    create table cmd_log(
    id int primary key auto_increment,
    cmd_name char(64), #命令的名字
    sub_time datetime, #提交时间
    user_name char(32), #是哪个用户过来执行这个命令
    is_success enum('yes','no')  #命令是否执行成功
    );
    
    create table err_log(
    id int primary key auto_increment,
    cname char(64), #命令的名字
    stime datetime #提交时间
    );

    创建触发器

    -- #创建触发器(向err_log表里插入最新的记录)
    delimiter //
    create
      trigger tri_after_inser_cmd_log
      after insert
      on cmd_log for  each row
    BEGIN
      if new.is_success = 'no' then
        insert into err_log(cname,stime) VALUES(new.cmd_name,new.sub_time);
      end if;  #记得加分号,mysql一加分号代表结束,那么就得声明一下
    END //
    delimiter ;  #还原的最原始的状态
    
    
    -- #创建触发器(向err_log表里插入最旧的记录)
    delimiter //
    create
      trigger tri_after_inser_cmd_log1
      after delete
      on cmd_log for  each row
    BEGIN
      if old.is_success = 'no' then
        insert into err_log(cname,stime) VALUES(old.cmd_name,old.sub_time);
      end if;  #记得加分号,mysql一加分号代表结束,那么就得声明一下
    END //
    delimiter ;  #还原的最原始的状态
    DELETE from cmd_log where id=1;

     

    -- 触发器的两个关键字:new ,old
    -- new :表示新的记录
    -- old:表示旧的那条记录
    -- 什么情况下才往里面插记录
    --    当命令输入错误的时候就把错误的记录插入到err_log表中
    1. 插入事件触发器
    INSERT INTO order_table(gid,much) VALUES(1,3);
    
    -- update goods set num = num -3 where id =1;
    
    CREATE TRIGGER tg1 AFTER INSERT on order_table
    for EACH row -- 固定写法
    BEGIN
        update goods set num = num -new.much where id =new.gid;
    END
    
    -- 删除触发器
    drop TRIGGER TG1;
    
    2.更新事件触发器
        update order_table set much = much +2 where oid = 6;
    
        update goods set num = num+2 where id = 1;
    
        create TRIGGER tg2 AFTER UPDATE ON order_table
        for EACH ROW
        BEGIN
            update goods set num = num+old.much - new.much where id = old.gid;
        END
    3.删除事件触发器
        DELETE FROM order_table where oid =6;
    
        update goods set num = num + 3 where id = 1;
    
        create TRIGGER tg3 AFTER DELETE on order_table
        for EACH ROW
        BEGIN
            update goods set num = num + old.much where id = old.gid;
        END
    4.查看触发器
        show tiggers;
  • 相关阅读:
    电感
    电容
    电阻
    函数异常规格说明
    异常处理深度解析
    自定义内存管理
    单例类模板
    数组类模板
    数组类模板
    类模板深度剖析
  • 原文地址:https://www.cnblogs.com/TheLand/p/8486730.html
Copyright © 2011-2022 走看看