2009-06-03 3 views
2

많은 유사한 질문을 &으로 보았지만 다른 DB 관련 트릭을 사용했거나 코드 등에서 사용했습니다. 직선형 SQL 배치 파일을 찾고 있습니다. 솔루션 (존재하는 경우).오라클 데이터베이스에 두 개의 관련 테이블로드

상위/하위 관계가있는 두 개의 테이블이 있는데 Runs & Run_Values라고합니다.
실행에는 "자동"PK, runID (트리거 & 트리거) 및 두 개의 열 Model_Type & (제약 조건이 적용된 행)을 고유하게 식별하는 시간이 있습니다. Run의 각 행마다 Run_d & Value라는 두 개의 열이있는 Run_Values에 많은 항목이 있습니다.

insert into Runs (Model_Type, Time) values ('model1', to_date('01-01-2009 14:47:00', 'MM-DD-YYYY HH24:MI:SS')); 
set someVariable = SELECT runId FROM Runs WHERE Model_Type like 'model1' and Time = to_date('01-01-2009 14:47:00', 'MM-DD-YYYY HH24:MI:SS')); 
insert into Run_Values (run_id, Value) values (someVariable, 1.0); 
etc - lots more insert statements with Values for this model run. 

어떤 생각, 참고 문헌 등 :

나는 (SQL의 혼합 내가 존재 알고 SQL 내가 그것을 원하는만큼) 데이터를 만드는 과정에서이 같은 것을 생성하고 싶습니다 감사합니다.

답변

4

트릭은 시퀀스의 CURRVAL을 사용하는 것입니다. 데이터베이스 트리거에 설정되어 있어도 사용할 수 있습니다.

예 :

SQL> create table runs 
    2 (runid  number 
    3 , model_type varchar2(6) 
    4 , time  date 
    5 ) 
    6/

Table created. 

SQL> create sequence run_seq start with 1 increment by 1 cache 100 
    2/

Sequence created. 

SQL> create trigger run_bri 
    2 before insert on runs 
    3 for each row 
    4 begin 
    5 select run_seq.nextval 
    6  into :new.runid 
    7  from dual 
    8 ; 
    9 end; 
10/

Trigger created. 

SQL> create table run_values 
    2 (run_id number 
    3 , value number(3,1) 
    4 ) 
    5/

Table created. 

SQL> insert into runs (model_type, time) values ('model1', to_date('01-01-2009 14:47:00', 'mm-dd-yyyy hh24:mi:ss')); 

1 row created. 

SQL> insert into run_values (run_id, value) values (run_seq.currval, 1.0); 

1 row created. 

SQL> insert into run_values (run_id, value) values (run_seq.currval, 2.0); 

1 row created. 

SQL> insert into runs (model_type, time) values ('model2', to_date('01-01-2009 15:47:00', 'mm-dd-yyyy hh24:mi:ss')); 

1 row created. 

SQL> insert into run_values (run_id, value) values (run_seq.currval, 3.0); 

1 row created. 

SQL> insert into run_values (run_id, value) values (run_seq.currval, 4.0); 

1 row created. 

SQL> insert into run_values (run_id, value) values (run_seq.currval, 5.0); 

1 row created. 

SQL> select * from runs 
    2/

    RUNID MODEL_ TIME 
---------- ------ ------------------- 
     1 model1 01-01-2009 14:47:00 
     2 model2 01-01-2009 15:47:00 

2 rows selected. 

SQL> select * from run_values 
    2/

    RUN_ID  VALUE 
---------- ---------- 
     1   1 
     1   2 
     2   3 
     2   4 
     2   5 

5 rows selected. 

감사 롭.

+0

감사합니다. 한 가지 질문입니다. 현재 프로세스/세션이 이전 프로세스의 결과를 삽입하는 동안 다른 프로세스/세션이 새로운 모델을 생성하면 어떻게됩니까? 이 세션/거래의 currval 만입니까? – Marc

+0

좋은 질문입니다, Marc. 예, CURRVAL은 세션 용이며 다른 세션의 영향을받지 않습니다. – spencer7593

+0

예, currval은 현재 세션에서만 작동합니다. 다른 세션이 새 실행을 삽입하면 시퀀스가 ​​증가하지만 다른 세션의 currval은 동일하게 유지됩니다. –