触发器实现多表之间的增加、删除及更新

注:本文参考http://blog.sina.com.cn/s/blog_a0912d340101gxhb.html

常见的触发器有三种:分别应用于Insert,Update,Delete事件。

1.数据同步增加

如有两张表:A表和B表,创建触发器使当A表插入数据后B表也同步插入数据。其中B表插入数据的字段需要同A表中的字段相对应。

1 create trigger 触发器名称
2 on A表
3 after insert
4 as 
5 begin insert into B表(B表字段1,B表字段2,B表字段3)
6 select A表字段1,A表字段2,A表字段3
7 from inserted
8 end

实例测试:

实现若Info_Stu有新的数据插入,则将数据的Name提取出,同步到Info_Borrow表

1 create trigger triCopy_Stu2Borrow
2 on Info_Stu
3 after insert
4 as 
5 begin insert into Info_Borrow(Name) 
6 select Name from Info_Stu
7 end

测试效果如下:

 

2.数据同步删除

如有两张表:A表和B表,创建触发器使当A表删除数据后B表也能同步删除数据。其中B表与A表应有相应主键关联。

1 create trigger 触发器名称
2 on A表
3 after delete
4 as begin delete B表
5 where B表主键 inselect A表主键 from deleted)
6 end

实例测试:

删除Info_Stu中的一条记录时,删除Info_Borrow中相同的记录

1 create trigger triDelete_Stu2Borrow
2 on Info_Stu
3 after delete
4 as begin delete Info_Borrow
5 where Name in (select Name from deleted)
6 end

测试效果如下:

 

3.数据同步更新

如有两张表:A表和B表,创建触发器使当A表数据更新后B表也同步更新数据。

 1 create trigger 触发器名称
 2 on A表
 3 after update
 4 as begin
 5 update B表
 6 set
 7 B.B表字段1=i.字段1
 8 from 
 9 B表  B, deleted d,inserted  i
10 WHERE B.B表字段=d.字段

测试效果如下:

1 create trigger triUpdate_Stu2Borrow
2 on Info_Stu
3 after update
4 as
5 begin update Info_Borrow set Name=i.Name
6    from Info_Borrow as br,deleted d, inserted as i
7    where br.Name=d.Name
8 end

 

注:数据更新的操作涉及到了临时表的建立:

理解触发器里面的两个临时的表:deleted,inserted。注意deleted与inserted分别表示触发事件的表“旧的一条记录”和“新的一条记录”。

一个数据库系统中有两个虚拟表用于存储在表中记录改动的信息,分别是:

 虚拟表inserted虚拟表deleted
在表记录新增时存放新增的记录不存储记录
修改时存放用来更新的新纪录存放更新前的记录
删除时不存储记录存放被删除的记录

转载于:https://www.cnblogs.com/imstrive/p/4760104.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值