首页 > 代码库 > SQL Server 触发器

SQL Server 触发器

触发器是一种特殊类型的存储过程,它不同于之前的我们介绍的存储过程。触发器主要是通过事件进行触发被自动调用执行的。而存储过程可以通过存储过程的名称被调用。

Ø 什么是触发器

    触发器对表进行插入、更新、删除的时候会自动执行的特殊存储过程。触发器一般用在check约束更加复杂的约束上面。触发器和普通的存储过程的区别是:触发器是当对某一个表进行操作。诸如:update、insert、delete这些操作的时候,系统会自动调用执行该表上对应的触发器。SQL Server 2005中触发器可以分为两类:DML触发器和DDL触发器,其中DDL触发器它们会影响多种数据定义语言语句而激发,这些语句有create、alter、drop语句。

 

    DML触发器分为:

    1、 after触发器(之后触发)

        a、 insert触发器

        b、 update触发器

        c、 delete触发器

 

    2、 instead of 触发器 (之前触发)

 

    其中after触发器要求只有执行某一操作insert、update、delete之后触发器才被触发,且只能定义在表上。而instead of触发器表示并不执行其定义的操作(insert、update、delete)而仅是执行触发器本身。既可以在表上定义instead of触发器,也可以在视图上定义。

 

    触发器有两个特殊的表:插入表(instered表)和删除表(deleted表)。这两张是逻辑表也是虚表。有系统在内存中创建者两张表,不会存储在数据库中。而且两张表的都是只读的,只能读取数据而不能修改数据。这两张表的结果总是与被改触发器应用的表的结构相同。当触发器完成工作后,这两张表就会被删除。Inserted表的数据是插入或是修改后的数据,而deleted表的数据是更新前的或是删除的数据。

 

 

对表的操作

Inserted逻辑表

Deleted逻辑表

增加记录(insert)

存放增加的记录

删除记录(delete)

存放被删除的记录

修改记录(update)

存放更新后的记录

存放更新前的记录

 

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

 

Ø 创建触发器

    语法

Create Trigger tgr_nameOn table_name   With encrypion –加密触发器For  Update...As    Transact -Sql

# 创建insert类型触发器

/************************************************************ * Code formatted by SoftTree SQL Assistant ?v6.0.70 * Time: 2014-10-15 10:42:34 ************************************************************/--创建insert插入类型触发器If (Object_id(tgr_classes_insert, tr) Is Not Null)    Drop Trigger tgr_classes_insertGoCreate Trigger tgr_classes_insertOn classesFor  Insert--插入触发As    --定义变量    Declare @id Int, @name Varchar(20), @temp Int;    --在inserted表中查询已经插入记录信息    Select @id = id, @name = Name    From   Inserted;    Set @name = @name + Convert(Varchar, @id);    Set @temp = @id / 2;        Insert Into student    Values      (        @name, 18 + @id, @temp, @id      );    Print 添加学生成功!;Go--插入数据Insert Into classesValues  (    5班, Getdate()  );--查询数据Select *From   classes;Select *From   studentOrder By       id;

insert触发器,会在inserted表中添加一条刚插入的记录。

 

# 创建delete类型触发器

--delete删除类型触发器If (Object_id(tgr_classes_delete, TR) Is Not Null)    Drop Trigger tgr_classes_deleteGoCreate Trigger tgr_classes_deleteOn classesFor  Delete--删除触发As    Print 备份数据中……;        If (Object_id(classesBackup, U) Is Not Null)        --存在classesBackup,直接插入数据        Insert Into classesBackup        Select Name, createDate        From   Deleted;    Else    --不存在classesBackup创建再插入    Select * Into classesBackup    From   Deleted;    Print 备份数据成功!;Go----不显示影响行数--set nocount on;Delete classesWhere  Name = 5班;--查询数据Select *From   classes;Select *From   classesBackup;

delete触发器会在删除数据的时候,将刚才删除的数据保存在deleted表中。

 

# 创建update类型触发器

--update更新类型触发器If (Object_id(tgr_classes_update, TR) Is Not Null)    Drop Trigger tgr_classes_updateGoCreate Trigger tgr_classes_updateOn classesFor  UpdateAs    Declare @oldName Varchar(20), @newName Varchar(20);    --更新前的数据    Select @oldName = Name    From   Deleted;    If (           Exists (               Select *               From   student               Where  Name Like % + @oldName + %           )       )    Begin        --更新后的数据        Select @newName = Name        From   Inserted;        Update student        Set    Name = Replace(Name, @oldName, @newName)        Where  Name Like % + @oldName + %;        Print 级联修改数据成功!;    End    Else        Print 无需修改student表!;Go--查询数据Select *From   studentOrder By       id;Select *From   classes;Update classesSet    Name  = 五班Where  Name  = 5?

update触发器会在更新数据后,将更新前的数据保存在deleted表中,更新后的数据保存在inserted表中。

 

# update更新列级触发器

If (Object_id(tgr_classes_update_column, TR) Is Not Null)    Drop Trigger tgr_classes_update_columnGoCreate Trigger tgr_classes_update_columnOn classesFor  UpdateAs    --列级触发器:是否更新了班级创建时间    If (Update(createDate))    Begin        Raiserror(系统提示:班级创建时间不能修改!, 16, 11);        Rollback Tran;    EndGo--测试Select *From   studentOrder By       id;Select *From   classes;Update classesSet    createDate = Getdate()Where  id = 3;Update classesSet    Name  = 四班Where  id    = 

 更新列级触发器可以用update是否判断更新列记录;

 

# instead of类型触发器

       instead of触发器表示并不执行其定义的操作(insert、update、delete)而仅是执行触发器本身的内容。

       创建语法

Create Trigger tgr_nameOn table_name   With Encryption   Instead Of Update...As    T -Sql

# 创建instead of触发器

if (object_id(tgr_classes_inteadOf, TR) is not null)    drop trigger tgr_classes_inteadOfgocreate trigger tgr_classes_inteadOfon classes    instead of delete/*, update, insert*/as    declare @id int, @name varchar(20);    --查询被删除的信息,病赋值    select @id = id, @name = name from deleted;    print id:  + convert(varchar, @id) + , name:  + @name;    --先删除student的信息    delete student where cid = @id;    --再删除classes的信息    delete classes where id = @id;    print 删除[ id:  + convert(varchar, @id) + , name:  + @name +  ] 的信息成功!;go--testselect * from student order by id;select * from classes;delete classes where id = 7;

# 显示自定义消息raiserror

If (Object_id(tgr_message, TR) Is Not Null)    Drop Trigger tgr_messageGoCreate Trigger tgr_messageOn student   After Insert, UpdateAs    Raiserror(tgr_message触发器被触发, 16, 10);Go--testInsert Into studentValues  (    lily, 22, 1, 7  );Update studentSet    sex = 0Where  Name = lucy;Select *From   studentOrder By       id;

# 修改触发器

alter trigger tgr_messageon studentafter deleteas raisError(tgr_message触发器被触发, 16, 10);go--testdelete from student where name = lucy;

# 启用、禁用触发器

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

# 查询创建的触发器信息

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

# 示例,验证插入数据

if ((object_id(tgr_valid_data, TR) is not null))    drop trigger tgr_valid_datagocreate trigger tgr_valid_dataon studentafter insertas    declare @age int,            @name varchar(20);    select @name = s.name, @age = s.age from inserted s;    if (@age < 18)    begin        raisError(插入新数据的age有问题, 16, 1);        rollback tran;    endgo--testinsert into student values(forest, 2, 0, 7);insert into student values(forest, 22, 0, 7);select * from student order by id;

# 示例,操作日志

if (object_id(log, U) is not null)    drop table loggocreate table log(    id int identity(1, 1) primary key,    action varchar(20),    createDate datetime default getDate())goif (exists (select * from sys.objects where name = tgr_student_log))    drop trigger tgr_student_loggocreate trigger tgr_student_logon studentafter insert, update, deleteas    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);    endgo--testinsert 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;

 

SQL Server 触发器