zoukankan      html  css  js  c++  java
  • 触发器(2)

    1、DML触发器分为两种(AFTER触发器和INSTEAD OF触发器)
    AFTER触发器(之后触发)
      也叫FOR触发器,after触发器要求只有执行某一操作insert、update、delete之后触发器才被触发,且只能定义在表上。(AFTER 触发器只能在表上指定,且动作晚于约束处理。)
    INSTEAD OF 触发器(之前触发)
      而instead of触发器表示并不执行其定义的操作(insert、update、delete)而仅是执行触发器本身。既可以在表上定义instead of触发器,也可以在视图上定义。
      触发器有两个特殊的表:插入表(instered表)和删除表(deleted表)。这两张是逻辑表也是虚表。有系统在内存中创建者两张表,不会存储在数据库中。而且两张表的都是只读的,只能读取数据而不能修改数据。这两张表的结果总是与被改触发器应用的表的结构相同。当触发器完成工作后,这两张表就会被删除。Inserted表的数据是插入或是修改后的数据,而deleted表的数据是更新前的或是删除的数据。(INSTEAD OF 触发器的动作要早于表的约束处理)

    对表的操作 Inserted逻辑表 Deleted逻辑表
    增加记录(insert) 存放增加的记录
    删除记录(delete) 存放被删除的记录
    修改记录(update) 存放更新后的记录 存放更新前的记录

      Update数据的时候就是先删除表记录,然后增加一条记录。这样在inserted和deleted表就都有update后的数据记录了。注意的是:触发器本身就是一个事务,所以在触发器里面可以对修改数据进行一些特殊的检查。如果不满足可以利用事务回滚,撤销操作。

    2、启用禁用触发器

    --禁用触发器
    disable trigger tgr_message on student;
    --启用触发器
    enable trigger tgr_message on student;

    3、查询创建的触发器信息

    --查询已存在的触发器
    select * from sys.triggers;
    select * from sys.objects where type = 'TR';
    
    --查看触发器触发事件
    select te.* from sys.trigger_events te join sys.triggers t
    on t.object_id = te.object_id
    where t.parent_class = 0 and t.name = 'tgr_valid_data';
    
    --查看创建触发器语句
    exec sp_helptext 'tgr_message';

     4、# 示例,操作日志

    if (object_id('log', 'U') is not null)
        drop table log
    go
    create table log(
        id int identity(1, 1) primary key,
        action varchar(20),
        createDate datetime default getDate()
    )
    go
    if (exists (select * from sys.objects where name = 'tgr_student_log'))
        drop trigger tgr_student_log
    go
    create trigger tgr_student_log
    on student
    after insert, update, delete
    as
        if ((exists (select 1 from inserted)) and (exists (select 1 from deleted)))
        begin
            insert into log(action) values('updated');
        end
        else if (exists (select 1 from inserted) and not exists (select 1 from deleted))
        begin
            insert into log(action) values('inserted');
        end
        else if (not exists (select 1 from inserted) and exists (select 1 from deleted))
        begin
            insert into log(action) values('deleted');
        end
    go
    --test
    insert into student values('king', 22, 1, 7);
    update student set sex = 0 where name = 'king';
    delete student where name = 'king';
    select * from log;
    select * from student order by id;
  • 相关阅读:
    MicXP程序爱好者
    cnblogs上的mysql学习心得
    iwebship 购物系统 PHP lamp环境
    可以购买的网址
    模板网址
    学习ecshop 教程网址
    ecshop数据库操作函数
    yzoj1568: 数字组合 题解
    yzoj1891 最优配对问题 题解
    yzoj1985 最长公共单调上升子序列 题解
  • 原文地址:https://www.cnblogs.com/AngelLee2009/p/3342587.html
Copyright © 2011-2022 走看看