基本概念:触发器是一种不能被显示调用的特殊存储过程。
使用时机:给一个表添加了相关的触发器后,当对这个表执行insert,update或Delete操作时触发器会被激活(触发)。
作用:通过触发器可以实现添加更加复杂的完整性约束;或者对不同表的相关字段或数据更新任务等。比如添加一条进货信息,会同时更新库存和采购订单数据。
缺点:触发器后期维护关联内容太多的时候,很容易出问题的,一般可以用存储过程代替。
【触发器的两种表】:Inserted和Deleted表,由系统维护,在内存中的临时表。Inserted和Deleted表结构和触发器所在的表结构相同。触发器执行完毕后,这两个表自动删除。
Inserted表:当执行Insert语句时,除了在当前数据表中真实的插入一个数据外,同时在Inserted临时表中插入一条数据。
Deleted表:当执行Delete或Update语句时,删除的或修改前的数据会存放到此表。
注意:当修改一条数据的时候,首先把修改前的数据,插入到deleted表。然后把修改后的数据插入到inserted表中。
当删除一条数据的时候,只是在deleted表中插入已经删除的数据。
当插入一条数据的时候,只是在inserted表中插入一条新的数据。
触发器类型:
instead of触发器:除表作用与表之外,Instead of 触发器也可以用于视图,用来扩展视图可以支持的更新操作。
after触发器:在insert。Update、Delete语句执行后,进行复杂业务处理,或进行约束检查等。
after触发器只能用于表。
use SaleManagerDB
go
--c创建insert触发器
if exists(select *from sysobjects where name='ProductStorage_Insert')
drop trigger ProductStorage_Insert
go
create trigger ProductStorage_Insert
on ProductStorage after insert
as
declare @ProductId varchar(50),@AddedCount int
--从插入的inserted临时表中获取数据
select @ProductId=ProductId,@AddedCount=AddedCount from inserted
--更新库存表中对应商品的库存数据
update ProductInventory set TotalCount=TotalCount+@AddedCount where ProductId=@ProductId
go
创建update触发器
if exists(select *from sysobjects where name='ProductInventory_update')
drop trigger ProductInventory_update
go
create trigger ProductInventory_update
on ProductInventory after update
as
declare @ProductId varchar(50),@totalCount int
--从插入的临时表中获取商品ID和商品库存数据
select @ProductId=ProductId,@totalCount from inserted
--根据当前的库存数量更新商品的库存状态
update ProductInventory set StatusId=case
when @totalCount>MaxCount then 2
when @totalCount<MinCount and @totalCount>0 then -1
when @totalCount=0 then -2
else 1
end where ProductId=@ProductId
go