plsql 触发器教程-当表1的某条数据更新时,表2的某些数据也自动更新

来源:互联网 发布:office for mac下架了? 编辑:程序博客网 时间:2024/05/16 10:54

触发器-update


需求:一张表的某个字段跟随另一张表的某个字段的值更新而更新

2张表


 test001表




test002表:







新建触发器,当更新test001中的D为某个值x时,test002中的D(不一定是D,也可以是C)也变成x

例如:update test001 t1 set D='7'where t1.A='1';

当我手动更新test001表中 a字段为1的那条记录 ,把d更新为7时,那么要使test002表中a字段也为1的那条记录,自动更新为7,

那么触发器可以这样写:

     


create or replace trigger Test02Trafter update of don test001for each rowbeginupdate test002  t2 set t2.d = :new.d where exists (select * from test002where  t2.a=:new.a);end test02Tr;


 

需要注意的地方   new.字段表示的是在执行完某个更新操作后的那条数据记录,如果这里没有使用new.字段而是使用 test001的话,则会报错:



错误sql:

create or replace trigger Test02Trafter update of don test001for each rowbeginupdate test002 t2set t2.d = :new.dwhere exists (select *from test002 t3,test001 t1where t1.a =t2.a);end test02Tr;

 

最后,测试:

update test001 t1 set D='7'where t1.A='1';

执行完之后,2张表的D字段的值都是7

 


如有疑问或改进的地方请指出,共同进步!



本文已获原作者授权

原贴链接:http://blog.csdn.net/qq_39678382/article/details/78551472




更多关于触发器的一些语法,比如为什么用for each row,不用for each statement 等,这些都是视具体情况的,

这些细节的使用,可以参考以下的文章:

1、http://blog.csdn.net/lcb0913/article/details/6655499


2、https://www.cnblogs.com/eastsea/p/3788372.html

这两篇把触发器的基本概念说的都很详细,大家可以参考以下。





阅读全文
0 0
原创粉丝点击