Oracle中,当需要建立一个自增字段时,需要用到sequence。sequence也可以在mysql中使用,但是有些差别,日后再补充,先把oracle中sequence的基本使用总结一下,方便日后查阅。
1、创建sequence:
[sql] view plain copy
- 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:
[sql] view plain copy
- select * from user_sequences;
3、删除指定sequence:
[sql] view plain copy
- DROP SEQUENCE SEQ_ON_USER;
4、查看指定sequence的当前值:
两种方式:
[sql] view plain copy
- select last_number from user_sequences wheresequence_name=‘SEQ_ON_USER‘;
[sql] view plain copy
- select SEQ_ON_USER.nextval from sys.dual;
5、创建触发器使用sequence设置主键自动插入。
[sql] view plain copy
- 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插入主键值。
原文地址:https://www.cnblogs.com/aliyunpang/p/9082598.html
时间: 2024-10-08 22:23:56