Oracle中 级联删除和更新

在Oracle中使用on delete cascade 可以实现级联删除的操作
代码如下:

--create table a and b
Create Table department (dept_id   number (4) Not Null Primary Key, name      varchar2 (10), importdate date default sysdate);

Create Table employee (
                       emp_id       number (4) Not Null Primary Key,
                       dept_id      number (4),
                       name         varchar2 (10),
                       importdate   date default sysdate
                      );

Alter Table employee Add Constraint emp_fk Foreign Key (dept_id) References department(dept_id) on delete cascade;
commit;

级联更新如下:
create table a(
id number not null primary key deferrable,
modifydate date default sysdate
);

create table b(
id number not null primary key,
a_id number
constraint a_id_fk foreign key(a_id) references a(id) on delete cascade
);

create or replace trigger trg_b_a_id 
after update of id on a for each row
begin
  update b set a_id=:NEW.id where a_id=:OLD.id;
end;

SQL> select * from b;
        ID       A_ID
---------- ----------
         1          1
         2          4
         3          3


SQL> select * from a;
        ID NAME
---------- -------------
         1 test_1
         4 test_3
         3 test_2

SQL> update a set id=5 where id=1;

更新基本表后:
SQL> select * from a;
        ID NAME
---------- ------------
         5 test_1
         4 test_3
         3 test_2


SQL> select * from t;
        ID       A_ID
---------- ----------
         1          5
         2          4
         3          3

你可能感兴趣的:(oracle,sql)