觸發器是一種特殊類型的預存程序,它不同於之前的我們介紹的預存程序。觸發器主要是通過事件進行觸發被自動調用執行的。而預存程序可以通過預存程序的名稱被調用。
Ø 什麼是觸發器
觸發器對錶進行插入、更新、刪除的時候會自動執行的特殊預存程序。觸發器一般用在check約束更加複雜的約束上面。觸發器和普通的預存程序的區別是:觸發器是當對某一個表進行操作。諸如:update、insert、delete這些操作的時候,系統會自動調用執行該表上對應的觸發器。SQL Server 2005中觸發器可以分為兩類:DML觸發器和DDL觸發器,其中DDL觸發器它們會影響多種資料定義語言 (Data Definition Language)語句而激發,這些語句有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_namewith encrypion –加密觸發器for update...asTransact-SQL # 建立insert類型觸發器--建立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 classes values('5班', getDate());--查詢資料select * from classes;select * from student order 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 --刪除觸發asprint '備份資料中……'; 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 classes where 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 updateasdeclare @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 '級聯修改資料成功!';endelseprint '無需修改student表!';go--查詢資料select * from student order by id;select * from classes;update classes set 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))beginraisError('系統提示:班級建立時間不能修改!', 16, 11);rollback tran;endgo--測試select * from student order by id;select * from classes;update classes set createDate = getDate() where id = 3;update classes set name = '四班' where id = 7;
更新列級觸發器可以用update是否判斷更新列記錄;
# instead of類型觸發器
instead of觸發器表示並不執行其定義的操作(insert、update、delete)而僅是執行觸發器本身的內容。
建立文法
create trigger tgr_nameon table_namewith encryptioninstead of update...asT-SQL # 建立instead of觸發器if (object_id('tgr_classes_inteadOf', 'TR') is not null)drop trigger tgr_classes_inteadOfgocreate trigger tgr_classes_inteadOfon classesinstead of delete/*, update, insert*/asdeclare @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; # 顯示自訂訊息raiserrorif (object_id('tgr_message', 'TR') is not null)drop trigger tgr_messagegocreate trigger tgr_messageon studentafter insert, updateas raisError('tgr_message觸發器被觸發', 16, 10);go--testinsert into student values('lily', 22, 1, 7);update student set sex = 0 where name = 'lucy';select * from student order 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 insertasdeclare @age int,@name varchar(20);select @name = s.name, @age = s.age from inserted s;if (@age < 18)beginraisError('插入新資料的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, deleteasif ((exists (select 1 from inserted)) and (exists (select 1 from deleted)))begininsert into log(action) values('updated');endelse if (exists (select 1 from inserted) and not exists (select 1 from deleted))begininsert into log(action) values('inserted');endelse if (not exists (select 1 from inserted) and exists (select 1 from deleted))begininsert 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;