通过存储函数获取序列

实际应用程序开发过程中,大部分业务表是由程序进行增删改,为避免冲突通常会配置序列表来配置序列生成规则。也部分表由运维人员进行配置,如系统控制参数等配置,程序不直接做增删改;

如果当前需求需要新增新的控制参数,由开发人员提供脚本,运维执行;

通常在插入数据时,主键的生成,通常采用的是max(t.id)+1,可能会出现序列表的值小于数据表值情况,导致实际程序运行获取序列插入主键冲突的情况。

 

create or replace function f_sequence(i_busi_serial_name in varchar2, i_num in number) return number is
v_current number(15);
pragma autonomous_transaction;
begin
begin
select a.sequence into v_current from carefx_table_seq a where a.table_name = i_busi_serial_name for update;
exception
//当序列表(carefx_table_seq)不存在该表序列数据时,插入序列记录;
when no_data_found then
insert into carefx_table_seq(table_name,sequence) values (i_busi_serial_name,1);
–查询出当前序列值
select a.sequence into v_current from carefx_table_seq a where a.table_name = i_busi_serial_name for update;
end;
//将当前序列表对应序列值+1;
update carefx_table_seq a set a.sequence = a.sequence + decode(i_num,null,1,i_num) where a.table_name = i_busi_serial_name;
commit;
//返回查询的序列值;
return(v_current);
exception when others then
rollback;
return null;

end f_sequence_gen;

carefx_table_seq:序列表
存在序列表配置的业务表:
使用 select f_sequence_gen(‘bi’,1) from dual,替换 select max(t.id)+1 from bi t;
对于通过业务序列来进行数据手动插入的业务表,使用上述存储函数来获取序列值:

 

 

 

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐