日期:2014-05-17  浏览次数:20797 次

数据库问题?求解答
oracle数据库,怎么实行主表和子表的数据同时添加,比如说订单表和订单明细表,当我在一个表单里面添加时,那么明细表的外键,也就是订单表的主键怎么获取到明细表中,听别人说用事务或触发器,做了下,没有做出来,请大哥们解答

------解决方案--------------------

create table dept(deptid int);
create table emp(empid int, deptid int);

create or replace trigger trg_test
before insert or update of deptid on emp for each row
begin

    insert into dept(deptid) 
    select :new.deptid
      from dual
     where not exists(select * from dept where deptid = :new.deptid);
end;


SQL> insert into emp(empid, deptid) values (1, 1); 
1 row inserted 
SQL> select * from dept; 
                                 DEPTID
---------------------------------------
                                      1 
SQL> insert into emp(empid, deptid) values (2, 2); 
1 row inserted 
SQL> select * from dept; 
                                 DEPTID
---------------------------------------
                                      1
                                      2 
SQL> update emp set deptid = 3 where empid = 1; 
1 row updated 
SQL> select * from dept; 
                                 DEPTID
---------------------------------------
                                      1
                                      2
                                      3
我不喜欢触发器。。。
------解决方案--------------------
支持1楼的做法,用触发器更好
------解决方案--------------------
不太建议用触发器
1)要么在程序中控制
1)要么表结构考虑重建一下,利用约束,ON UPDATE CASCADE的关键字