Oracle写的触发器

时间:2022-12-29 05:11:26

Q:有两个表
create table test1 (tid number,tname varchar2(20))
create table test2 (tid2 number,tname2 varchar2(20)

当test1的tname 被修改时 test2的tname2也同样被修改

A:create table t1(
id number,
tname varchar2(20)
)

create table t2(
id number,
tname varchar2(20)
)


insert into t1(id,tname) values(1,'aaa');
  insert into t1(id,tname) values(2,'bbb');
  insert into t1(id,tname) values(3,'ccc');


insert into t2(id,tname) values(1,'aaa');
  insert into t2(id,tname) values(2,'bbb');
  insert into t2(id,tname) values(3,'ccc');


create or replace trigger t1_trigger
  after update on t1
  for each row
  begin
    dbms_output.put_line('old is: '||:old.id);
    update t2 set tname = :new.tname where id=:old.id;
  end;
 
 
update t1 set tname ='cba' where id = 1

SQL> select * from t1;

        ID TNAME
---------- --------------------
        1 cba
        2 bbb
        3 ccc

SQL> select * from t2;

        ID TNAME
---------- --------------------
        1 cba
        2 bbb
        3 ccc