首页 > 代码库 > SQL Server ——触发器

SQL Server ——触发器

触发器是一类特殊的存储过程,在对表UPDATE、INSERT或DELETE语句时自动执行。

例题1.

--例题1.利用触发器显示‘改变了一条数据’use mydb gocreate trigger tr_info_add on infofor insert,deleteasprint 改变了一条数据go

例题2.

技术分享

例题3.

--例题3:水果表改变numbers列时,向orderdetails表中添加数据水果编号,数量变化。go create trigger tr_fruit_buy2 on fruitfor update, insert ,deleteas--操作之前列的数据declare @num1 intselect @num1=numbers from deleted--操作之后的数据declare @num2 intselect @num2=numbers from inserted--数据差declare @num intset @num=@num1-@num2--从deleted表中取出水果编号declare @code varchar(50)select @code=ids from deleted--将数据差、水果编号输入orderdetails表insert into orderdetails (ordercode,[count]) values (@code,@num)goselect * from Fruit select * from OrderDetails --添加触发器,执行以下语句,触发两个触发器tr_fruitbuy和tr_fruit_buy2结果如下update Fruit set numbers=numbers-5 where Ids =k002select * from OrderDetails

技术分享

例题4

--例题:instead of触发器,删除info表的数据时,先删除work和family的数据,再删info相应的数据select * from Info select * from Work select * from Family gocreate trigger tr_person_deletet on infoinstead of deleteas--删除work相关数据      --取出需要的delete信息declare @code varchar(50)select @code=code from deleted      --删除delete from Work where InfoCode =@code --删除family相关数据delete from Family where InfoCode =@code --最后删除info表中的相关数据(info表是family表和work表的主表,最后才能执行删除)delete from info where code=@codego--添加触发器后执行删除delete from Info where Code =p002

技术分享

SQL Server ——触发器