Oracle ID 自增

实现Oracle Id自增

1、方法一(Oracle Version Oracle 12c版本支持)

create table app_student
(
id integer generated by default as identity
not null primary key,
createtime DATE not NULL
);

insert into app_student(createtime) values(sysdate);

2. 方法二 创建序列

创建表

CREATE TABLE APP_USER(
  ID number(20) NOT NULL PRIMARY KEY,
  Create_Time date NOT NULL
  
);

  

--创建序列
create sequence seq_app_user
minvalue 1000
nomaxvalue
start with 1000
increment by 1
nocycle --一直累加,不循环
--nocache --不缓存
cache 10; --缓存10条

  

创建触发器

--创建触发器,如果insert语句不知道ID自动插入增长值
CREATE OR REPLACE TRIGGER tr_app_user
BEFORE INSERT ON app_user FOR EACH ROW When (new.ID is null)
begin
  select seq_app_user.nextval into:new.ID  from dual;
end;

  

插入数据:

ID的格式由序列控制

insert into APP_USER(  Create_Time)
values( sysdate)

  

自己控制ID的格式

insert into APP_USER( ID,  Create_Time)
values(to_number(to_char(sysdate,'yyyymmddhh24miss') + seq_app_student.nextval), sysdate)

 id的格式为时间+序列 

原文地址:https://www.cnblogs.com/linlf03/p/9758994.html