我见过很多类似的问题&答案,但他们已经使用了其他特定于数据库的技巧,或者在代码中完成了它等等。我正在寻找一个直接的SQL批处理文件解决方案(如果存在)。
我有两张父/子关系表,称之为Runs& Run_Values。
运行具有“自动”生成的PK,runID(顺序和触发器),以及两个列,Model_Type& ALSO唯一标识行的时间(使用约束强制执行)。对于Run中的每一行,Run_Values中有许多条目,它有两列,RunId&值。
我想从生成数据的过程中生成这样的东西(我知道存在的SQL和我喜欢的SQL的混合):
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.
任何想法,参考等都表示赞赏。
答案 0 :(得分: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.
此致 罗布。