oracle 实现自增auto_increament

在mysql中,实现字段自增,只用给他设置为auto_increase就ok了

这是简单的傻子啊(但是多数据库共享,分布式计算就不适用了,呵呵)

在oracle中没有这样便捷的功能,所以只能用sequence加trigger来解决这个问题

以下是一个Demo:

    创建sequence

-- create sequence of id of the table sql_template_set 
create sequence sql_template_id_seq
increment by 1
start with 60
nomaxvalue
nominvalue
nocache;

    创建表 sql_template_set (id为主键,并且为自增字段)

    create table SQL_TEMPLATE_SET

(
  SENTENCE    VARCHAR2(2000),
  TEMPLATESQL VARCHAR2(300),
  TABLEIDS    VARCHAR2(100),
  ID          NUMBER(6) not null
)
alter table SQL_TEMPLATE_SET
  add constraint TEMPLATE_ID primary key (ID)

    创建触发器,在insert数据之前,添加id的值

    -- 创建自增触发器

create or replace trigger sql_template_con_tri
before insert on sql_template_set for each row
begin
       -- 设置sql主键自增
      select sql_template_id_seq.nextval into :new.id from dual;
end;

    完毕,现在可以测试一下下

     -- 测试表trigger

insert into sql_template_set(sentence,templatesql,tableids) values('dirktest','dirktest','dirktest') 
commit;
 

    结果主键id就从60开始,每加条数据递增1

猜你喜欢

转载自blackproof.iteye.com/blog/1681336