天天看点

【曹操】oracle库表配置自增字段合计

前提:需要在字典表里设计自增字段。

1、需要添加自增字段的目标表

create table icondata.ccao_dictionary_info

(

  object_name varchar2(80),

  object_id   varchar2(20),

  parent_id   varchar2(20),

  update_user varchar2(50),

  update_time number,

  sort_id     number,

  option_type varchar2(50),

  sequ_id     number

)

2、创建序列

create sequence ccao_sequ_autoinc

minvalue 1

maxvalue 9999999999999999999999999999

start with 1

increment by 1

nocache;

修改cache大小:

alter sequence ccao_sequ_autoinc cache 20;

3、创建触发器

create or replace trigger insert_ccao_sequ_autoinc    --触发器名

  before insert on ccao_dictionary_info    --添加自增字段的表

  for each row

begin

  select ccao_sequ_autoinc.nextval into :new.sequ_id from dual;   --序列名

end;

或者设置一个中间变量nextid:

create or replace trigger insert_ccao_sequ_autoinc

  before insert on ccao_dictionary_info

declare

  nextid number;

  if :new.sequ_id is null or :new.sequ_id = 0 then

    select ccao_sequ_autoinc.nextval into nextid from dual;

    :new.sequ_id := nextid;

  end if;

4、查看序列创建结果,查看触发器创建结果

select * from all_triggers a where a.trigger_name='insert_ccao_sequ_autoinc';  

select * from user_sequences a where a.sequence_name = 'ccao_sequ_autoinc';

5、注意事项

(1)创建序列时,最好设置缓存,提高速率;

(2)创建触发器时,一定要注意触发器中,包含触发器名称、序列名和添加自增字段的目标表,千万不能弄错,不然触发器编译会出错,报错触发器器无效且验证不通过,一定是触发器写的有问题;

(3)一张表不能有多个触发器,因为触发器会全部出发,一旦有一个写错,所有的触发器都会无法执行,因此最好只写一个触发器。