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

注:本文参考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
在表记录新增时 存放新增的记录 不存储记录
修改时 存放用来更新的新纪录 存放更新前的记录
删除时 不存储记录 存放被删除的记录
菜鸟一枚,但有一颗不断进取的心; 兴趣所至,相信自己终会成功!!!!! 加油,imstrive
原文地址:https://www.cnblogs.com/imstrive/p/4760104.html