SQL Server 触发器的使用实例(2)
定义:
触发器是一种特殊的存储过程,在用户试图对指定的表执行指定的数据修改语句时自动执行。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