扩展了@Guru和@Ronnis的答案,你可以隐藏序列并使它看起来更像是一个使用触发器的自动增量,并有一个过程为你插入并返回生成的ID作为输出参数。
create table batch(batchid number,
batchname varchar2(30),
batchtype char(1),
source char(1),
intarea number)
/
create sequence batch_seq start with 1
/
create trigger batch_bi
before insert on batch
for each row
begin
select batch_seq.nextval into :new.batchid from dual;
end;
/
create procedure insert_batch(v_batchname batch.batchname%TYPE,
v_batchtype batch.batchtype%TYPE,
v_source batch.source%TYPE,
v_intarea batch.intarea%TYPE,
v_batchid out batch.batchid%TYPE)
as
begin
insert into batch(batchname, batchtype, source, intarea)
values(v_batchname, v_batchtype, v_source, v_intarea)
returning batchid into v_batchid;
end;
/
然后,您可以调用该过程而不是进行简单插入,例如,从一个不知名的块:
declare
l_batchid batch.batchid%TYPE;
begin
insert_batch(v_batchname => 'Batch 1',
v_batchtype => 'A',
v_source => 'Z',
v_intarea => 1,
v_batchid => l_batchid);
dbms_output.put_line('Generated id: ' || l_batchid);
insert_batch(v_batchname => 'Batch 99',
v_batchtype => 'B',
v_source => 'Y',
v_intarea => 9,
v_batchid => l_batchid);
dbms_output.put_line('Generated id: ' || l_batchid);
end;
/
Generated id: 1
Generated id: 2
您可以在没有显式匿名块的情况下进行呼叫,例如,从SQL * Plus:
variable l_batchid number;
exec insert_batch('Batch 21', 'C', 'X', 7, :l_batchid);
...并使用绑定变量:l_batchid
指所产生的价值算账:
print l_batchid;
insert into some_table values(:l_batch_id, ...);
这些是一些很好的答案。现在我正在完成任务,它看起来像另一个使用“包”的图层,将游标设置为“ROWTYPE”,并通过包内的过程或函数*返回一些数据将成为最后一步以结果集的形式返回数据,以便调用者可以执行SELECT,但将需要插入的数据作为参数传递给包函数。新的,所以希望这一切都有道理。 – Allbite 2011-05-09 21:38:32