因为Oracle中12c版本之前的都不能直接给主键设置自增长,所以只能通过序列+触发器来实现自增长。
大致过程:创建序列->创建触发器,并设置在某张表执行insert操作之前触发(让主键自增1【注意只能作用于为int类型的主键】)
两种方式创建:
一、SQL创建
1、SQL Window 执行语句创建序列:
create sequence test_autoinc--test_autoinc序列名
minvalue 1 --最小值
maxvalue 99999999999999999999999999 --最大值
start with 1--从1开始
increment by 1--每次加1
nocache;--不建缓冲区
2、SQL Window创建触发器:
create or replace trigger insert_test_id_autoinc --insert_test_id_autoinc触发器名称
before insert
on test --test 是表名
for each row
declare
-- local variables here(这里是局部变量)
nextid number;
begin
IF :new.test_id IS NULL or :new.test_id=0 THEN --test_id是列名
select test_autoinc.nextval --test_autoinc正是刚才创建的序列名
into nextid
from sys.dual;
:new.test_id:=nextid;--test_id是列名
end if;
end insert_test_id_autoinc ;--insert_test_id_autoinc触发器名称
3、再执行插入语句测试序列是否生效(没有设置id,插入成功后查看数据id是否自增):
insert into test (test_name,test_desc) values('test1','ceshi')
查看序列的SQL语句:
select * from user_sequences
二、图形界面手动创建序列:
2、创建触发器: