Oracle通过序列+触发器实现主键自增

时间:2023-03-09 08:29:20
Oracle通过序列+触发器实现主键自增

接触oracle没多久,在建表的时候发现还不会如何设置主键自动增长。和mysql的设置为AUTO_INCREMENT属性相比,要复杂很多,所以现在记录起来。

我使用的是序列+触发器的方式。

现在已经创建好一个tbl_dept表,比较简单就两个字段。建表语句如下:

-- Create table
create table TBL_DEPT
(
dept_id INTEGER not null,
dept_name VARCHAR2(255) not null
)
tablespace SYSTEM
pctfree 10
pctused 40
initrans 1
maxtrans 255
storage
(
initial 128K
next 1M
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table TBL_DEPT
add constraint PK_DEPT primary key (DEPT_ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);

表有了之后我们首先需要创建一个用来实现自动增长的序列:

create sequence sql_dept
minvalue 1 --最小值
nomaxvalue --不设置最大值
start with 1 --从1开始计数
increment by 1 --每次加1个
nocycle --一直累加,不循环
nocache; --不建缓冲区

最后我们只需要再把触发器设置好就行了:

create or replace trigger tg_dept
before insert on tbl_dept --tbl_dept:表名
for each row
declare
nextid number;
begin
IF :new.dept_id IS NULL or :new.dept_id=0 THEN --dept_id:列名
select sql_dept.nextval --sql_dept:序列
into nextid
from sys.dual;
:new.dept_id:=nextid;
end if;
end tg_dept;

插入前:

Oracle通过序列+触发器实现主键自增

我们现在通过插入语句来测试一下吧,我们插入的语句中主键dept_id为空:

insert into tbl_dept(dept_name) values('人事部');

结果:

Oracle通过序列+触发器实现主键自增