共计 1437 个字符,预计需要花费 4 分钟才能阅读完成。
Oracle 中,当需要建立一个自增字段时,需要用到 sequence。sequence 也可以在 mysql 中使用,但是有些差别,日后再补充,先把 Oracle 中 sequence 的基本使用总结一下,方便日后查阅。
1、创建 sequence:
create sequence SEQ_ON_USER
minvalue 1
maxvalue 999999999999999999999999999
start with 1
increment by 1
nocache;
说明:
minvalue:序列最小值
maxvalue/nomaxvalue:序列最大值 / 没有最大值
start with 1:序列从 1 开始
increment by 1:每次增加 1
cache/nocache:nocache 不缓存。cache 缓存。开启缓存,效率高,只是如果数据库宕机了,缓存丢失,会出现序列跳号情况。
2、查看已有 sequence:
select * from user_sequences;
select * from user_sequences;
3、删除指定 sequence:
DROP SEQUENCE SEQ_ON_USER;
DROP SEQUENCE SEQ_ON_USER;
4、查看指定 sequence 的当前值:
两种方式:
select last_number from user_sequences wheresequence_name=’SEQ_ON_USER’;
select last_number from user_sequences wheresequence_name=’SEQ_ON_USER’;
select SEQ_ON_USER.nextval from sys.dual;
select SEQ_ON_USER.nextval from sys.dual;
5、创建触发器使用 sequence 设置主键自动插入。
create or replace trigger “SEQ_ON_USER_GENERATOR” before
insert on databasename1.T_USER for each row
declare
mid number,
begin
select SEQ_ON_USER.nextval into mid from dual;
:new.id:=mid;
end
create trigger SEQ_ON_USER_Trigger
before insert on T_USER for each row
begin
select SEQ_ON_USER.nextval into :new.id from dual;
end SEQ_ON_USER_Trigger;
create or replace trigger “SEQ_ON_USER_GENERATOR” before
insert on databasename1.T_USER for each row
declare
mid number,
begin
select SEQ_ON_USER.nextval into mid from dual;
:new.id:=mid;
end
create trigger SEQ_ON_USER_Trigger
before insert on T_USER for each row
begin
select SEQ_ON_USER.nextval into :new.id from dual;
end SEQ_ON_USER_Trigger;
6、代码中使用 sequence.nextval 插入主键值。