做到这一点的唯一方法是使用代码控制表......
create table code_control
(year number(4,0) not null
, type varchar2(1) not null
, last_number number(38,0) default 1 not null
, primary key (year,type)
)
organization index
/
...这样维护...
create or replace function get_next_number
(p_year in number, p_type in varchar2)
return number
is
pragma autonomous_transaction;
cursor cur_cc is
select last_number + 1
from code_control cc
where cc.year= p_year
and cc.type = p_type
for update of last_number;
next_number number;
begin
open cur_cc;
fetch cur_cc into next_number;
if cur_cc%found then
update code_control
set last_number = next_number
where current of cur_cc;
else
insert into code_control (year,type)
values (p_year, p_type)
returning last_number into next_number;
end if;
commit;
return next_number;
end;
/
重要的是 SELECT ... FOR UPDATE。悲观锁定保证多用户环境中的唯一性。 PRAGMA 确保维护code_control
不会污染更广泛的交易。它允许我们在触发器中调用函数而不会出现死锁。
这是一张带有与您类似的密钥的表:
create table t42
(year number(4,0) not null
, type varchar2(1) not null
, id number(38,0)
, primary key (year,type, id)
)
/
create or replace trigger t42_trg
before insert on t42 for each row
begin
:new.id := get_next_number(:new.year, :new.type);
end;
/
在我入住之前我没什么可做的t42
:
SQL> select * from code_control;
no rows selected
SQL> select * from t42;
no rows selected
SQL> insert into t42 (year, type) values (2016, 'A');
1 row created.
SQL> insert into t42 (year, type) values (2016, 'A');
1 row created.
SQL> insert into t42 (year, type) values (2016, 'A');
1 row created.
SQL> insert into t42 (year, type) values (2016, 'B');
1 row created.
SQL> insert into t42 (year, type) values (2016, 'A');
1 row created.
SQL> insert into t42 (year, type) values (2017, 'A');
1 row created.
SQL> select * from t42;
YEAR T ID
---------- - ----------
2016 A 1
2016 A 2
2016 A 3
2016 A 4
2016 B 1
2017 A 1
6 rows selected.
SQL> select * from code_control;
YEAR T LAST_NUMBER
---------- - -----------
2016 A 4
2016 B 1
2017 A 1
SQL>
因此,对这种实现的明显反对是可扩展性。插入事务是序列化的code_control
桌子。这绝对是真的。然而,锁定的持有时间尽可能短,因此即使t42
表每秒填充多次。
但是,如果表受到大量并发插入,锁定可能会成为问题。该表具有足够的感兴趣事务槽(INITRANS、MAXTRANS)来应对并发需求,这一点至关重要。但非常繁忙的系统可能需要更智能的实现(可能批量生成 ID);否则放弃复合键,转而使用序列(因为序列在多用户环境中确实可以扩展)。