0

2つのテーブル間に1対多の関係があります。

table1:

NUMBER users_id (primary key)
field2
field3
...

table2:

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

INSERT入るとtable1、自動インクリメント(シーケンス?)して、同じレコードをすべてusers_idに挿入したいので、最終的にはtable2users_id

table1:

1,val1,val2

table2:

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

users_id自動インクリメントしtable1ての行を作成する シーケンスを持つトリガーが必要だと思いますtable2

関連性がないかもしれませんが、私はPHPスクリプトからこれを行っています。

アップデート

これまでのところ、シーケンスとトリガーを設定して、フィールドを自動インクリメントできるようにINSERTtable1てい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;

したがって、2番目のテーブルに自動的に挿入する必要があります。

どうもありがとう。

4

1 に答える 1

3

ステートメントreturning intoの句を使用して、新しいレコードがに挿入された後に値を返すことができます。また、シーケンスの現在の値を取得するために使用できます。次に例を示します(この例では、句の使用法を示すために単純なストアドプロシージャが実装されています。要件に応じて、同様のストアドプロシージャを実装できます)。insertusers_idtable1user_seq.currvalinsert 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;
于 2012-10-28T15:04:27.630 に答える