SQL Server ——触发器

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

例题1.

--例题1.利用触发器显示‘改变了一条数据’
use mydb 
go
create trigger tr_info_add on info
for insert,delete
as
print 改变了一条数据
go

例题2.

技术分享

例题3.

--例题3:水果表改变numbers列时,向orderdetails表中添加数据水果编号,数量变化。

go 
create trigger tr_fruit_buy2 on fruit
for update, insert ,delete
as
--操作之前列的数据
declare @num1 int
select @num1=numbers from deleted
--操作之后的数据
declare @num2 int
select @num2=numbers from inserted
--数据差
declare @num int
set @num=@num1-@num2
--从deleted表中取出水果编号
declare @code varchar(50)
select @code=ids from deleted
--将数据差、水果编号输入orderdetails表
insert into orderdetails (ordercode,[count]) values (@code,@num)
go

select * from Fruit 
select * from OrderDetails 
--添加触发器,执行以下语句,触发两个触发器tr_fruitbuy和tr_fruit_buy2结果如下
update Fruit set numbers=numbers-5 where Ids =k002
select * from OrderDetails

技术分享

例题4

--例题:instead of触发器,删除info表的数据时,先删除work和family的数据,再删info相应的数据
select * from Info 
select * from Work 
select * from Family 
go

create trigger tr_person_deletet on info
instead of delete

as
--删除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=@code
go

--添加触发器后执行删除
delete from Info where Code =p002

技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。