定義:
觸發器是一種特殊的預存程序,在使用者試圖對指定的表執行指定的資料修改語句時自動執行。Microsoft SQL Server 允許為任何給定的 Insert、Update 或 Delete 語句建立多個觸發器。
基本文法:(協助裡的文法太長了)
Create Trigger [TriggerName]
ON [TableName]
FOR [Insert][,Delete][,Update]
AS
--觸發器要執行的動作陳述式.
Go
注意:
觸發器中不允許以下 Transact-SQL 陳述式:
Alter DATABASE ,Create DATABASE,DISK INIT,
DISK RESIZE, Drop DATABASE, LOAD DATABASE,
LOAD LOG, RECONFIGURE, RESTORE DATABASE,
RESTORE LOG
觸發器使用執行個體:
程式碼1.) 建立測試用的表(testTable)
if exists (select * from sysobjects where id = object_id(N'testTable') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table testTable
GO
Create Table testTable(testField varchar(50))
2.) 建立基於表(testTable)的觸發器(testTrigger)
IF EXISTS (Select name FROM sysobjects Where name = 'testTrigger' AND type = 'TR')
Drop TRIGGER testTrigger
GO
Create Trigger testTrigger
ON testTable
FOR Insert,Delete,Update
AS
if exists(select * from inserted)
if exists(select * from deleted)
print '...更新'
else
print '...插入'
else
if exists(select * from deleted)
print '...刪除'
Go
3.) 操作testTable表,測試觸發器testTrigger
分別執行Insert Into語句,Update語句,Delete語句,看看效果
Insert Into testTable values ('testContent!')
Update testTable Set testField = 'UpdateContent'
Delete From testTable