在Oracle中触发以自动增加字段并插入关联表

时间:2012-10-28 14:37:14

标签: database oracle triggers oracle11g

我在两个表之间有一对多的关系:

table1:

NUMBER users_id (primary key)
field2
field3
...

table2:

NUMBER users_id (foreign key)
VARCHAR2 name
...
...

当我INSERT进入table1时,我想自动增加(序列?)users_id,并将多个记录插入table2所有相同的users_id 1}}所以我最终得到了

table1:

1,val1,val2

table2:

1,barry,...
1,bob,...
1,james,...

我想我需要一个带有序列的触发器,以便在users_id中自动增加table1并在table2中创建行。

它可能没有关系,但我是从PHP脚本执行此操作。

更新

到目前为止,我已经设置了序列和触发器,因此我可以INSERT进入table1并让users_id字段自动增加:

create sequence user_seq 
start with 1 
increment by 1 
nomaxvalue;

create trigger user_trigger
before insert on table1
for each row
begin
select user_seq.nextval into :new.users_id from dual;
end;

所以现在我只需要自动插入第二个表格。

非常感谢。

1 个答案:

答案 0 :(得分:3)

returning into中插入新记录后,您可以使用insert语句的users_id子句返回table1值。您还可以使用user_seq.currval来获取序列的当前值。下面是一个示例(在此示例中,已实现了一个简单的存储过程来演示insert into子句的用法。您可以根据您的要求实现类似的存储过程):

SQL> create table Tb_table_1(
  2    user_id number primary key,
  3    field_1 number
  4  );

Table created

SQL> 
SQL> create table Tb_table_2(
  2    user_id number references tb_table_1(user_id),
  3    name1 varchar2(17)
  4  );

Table created

SQL> create sequence user_seq
  2  start with 1
  3  increment by 1
  4  nomaxvalue;

Sequence created

SQL> 
SQL> create trigger user_trigger
  2  before insert on tb_table_1
  3  for each row
  4  begin
  5    select user_seq.nextval into :new.user_id from dual;
  6  end;
  7  /

Trigger created

  SQL> create or replace procedure Insert_Record
  2  is
  3    l_cur_id number;
  4  begin
  5    insert into Tb_table_1(Field_1)
  6      values(123)
  7    returning user_id into l_cur_id; -- store user_id of the new inserted record
  8    for i in 1..5                    -- in a local variable for later use  
  9    loop
 10      insert into tb_table_2(user_id, name1)  -- insert a bunch of sample data into table2 using previously stored user_id.
 11        values(l_cur_id, dbms_random.string('l', 7));
 12    end loop
 13    commit;
 14  end;
 15  /

Procedure created

SQL> select * from tb_table_1;

   USER_ID    FIELD_1
---------- ----------

SQL> select * from tb_table_2;

   USER_ID NAME1
---------- -----------------



SQL> exec insert_record;

PL/SQL procedure successfully completed

SQL> select * from tb_table_1
  2  ;

   USER_ID    FIELD_1
---------- ----------
         1        123

SQL> select * from tb_table_2;

   USER_ID NAME1
---------- -----------------
         1 jzsdbna
         1 ozbibgs
         1 btxrxcm
         1 hxwwpzc
         1 sdjbwzi

SQL> 

在Oracle 11g以后,您可以直接将序列值分配给变量:

:new.users_id := user_seq.nextval;