对于多用户环境来说,这是一个非常糟糕的主意,因为它会将插入序列化到表中.通常的方法是使用Oracle序列:
create sequence transaction_seq;
create trigger transaction_bir before insert on transaction
for each row
begin
:new.id := transaction_seq.nextval;
end;
Run Code Online (Sandbox Code Playgroud)
要编写实际获得最大当前值加1的基于触发器的解决方案,您需要编写复杂的3触发解决方案以避免"变异表"问题.或者您可以使用另一个表创建一个更简单的解决方案来保存当前最大值,如下所示:
create table transaction_max (current_max_id number);
insert into transaction_max values (0);
create trigger transaction_bir before insert on transaction
for each row
declare
l_current_max_id number;
begin
update transaction_max set current_max_id = current_max_id + 1
returning current_max_id into l_current_max_id;
:new.id := l_current_max_id;
end;
Run Code Online (Sandbox Code Playgroud)
这将避免变异表问题并将序列化(减慢)插入,因此我没有看到这比使用序列有任何优势.