创建触发器语法:
Create Trigger 触发器名字 On 表
FOR/INSTEAD OF/AFTER ---这里有三个选项:
-- for是针对什么的触发,也就是当执行某些操作的时候触发(insert,update,delete)
-- after是再操作之后触发,也就是当某些操作执行完的时候触发(insert,update,delete)
-- instead of 是替换这些操作(insert,update,delete)
Insert(, Update,delete)可以是一个或者多个的组合
AS
SQL语句
GO
例子1:表tb(id、名称、数量、单价、总价)的结构如下:
CREATE TABLE tb(Id int identity,Name nvarchar(50),Quantity int,UnitPrice int,TotalPrice int)
为表tb创建触发器tri_insert_update_on_tb,当insert或update表tb时,更新总价TotalPrice:
IF EXISTS (SELECT name FROM sys.objects WHERE name = 'tri_insert_update_on_tb' AND type = 'TR')
DROP TRIGGER tri_insert_update_on_tb
GO
CREATE trigger tri_insert_update_on_tb ON tb
FOR INSERT,UPDATE
AS
UPDATE tb SET TotalPrice = Quantity * UnitPrice WHERE Id=(SELECT Id FROM inserted)
GO
为表tb添加测试数据:
INSERT INTO tb(Name,Quantity,UnitPrice) VALUES('产品1',1,2)
INSERT INTO tb(Name,Quantity,UnitPrice) VALUES('产品2',2,2)
INSERT INTO tb(Name,Quantity,UnitPrice) VALUES('产品3',2,3)
INSERT INTO tb(Name,Quantity,UnitPrice) VALUES('产品4',4,4)
SELECT * FROM tb
查询结果可知触发器tri_insert_update_on_tb已经自动计算TotalPrice
Id Name Quantity UnitPrice TotalPrice
-----------------------------------------------
5 产品1 1 2 2
6 产品2 2 2 4
7 产品3 2 3 6
8 产品4 4 4 16
例子2:为表tb创建另一个触发器,当删除数据时把删除的数据放到另一个表tb2
创建表tb2:
CREATE TABLE tb2(Id int,Name nvarchar(50),Quantity int,UnitPrice int,TotalPrice int, SysId int identity,SysDate datetime default getdate())
创建触发器tri_delete_on_tb:
IF EXISTS (SELECT name FROM sys.objects WHERE name = 'tri_delete_on_tb' AND type = 'TR')
DROP TRIGGER tri_on_tb
GO
CREATE trigger tri_delete_on_tb on tb
FOR DELETE
AS
INSERT INTO tb2(Id,Name,Quantity,UnitPrice,TotalPrice) SELECT * from deleted
GO
删除表tb一条数据:
DELETE FROM tb where Id=8
结果:
SELECT * FROM tb
SELECT * FROM tb2
Id Name Quantity UnitPrice TotalPrice
------ -------- ----------- ----------- -----------
5 产品1 1 2 2
6 产品2 2 2 4
7 产品3 2 3 6
(3 行受影响)
Id Name Quantity UnitPrice TotalPrice SysId SysDate
------ ------- ----------- ----------- ----------- ----------- -----------------------
8 产品4 4 4 16 1 2009-10-27 22:31:03.197
(1 行受影响)
禁用: alter table 表名 disable trigger 触发器名启用: alter table 表名 enable trigger 触发器名