others linux服务器运维 django3 监控 k8s golang 数据库 大数据 前端 devops 理论基础 java oracle 运维日志

oracle 12c SEQUENCE 主键自增

访问量:1704 创建时间:2021-04-15

oracle 自增序列的作用,为表里面的自增字段设置值。

通过sqlplus或者datagrip等工具登陆oracle

Create Sequence

需要CREATE SEQUENCE或者CREATE ANY SEQUENCE权限

CREATE SEQUENCE seqTest
INCREMENT BY 1 -- 每次加几个,每次增加1
START WITH 1 -- 从1开始计数,序列从1开始
NOMAXvalue -- 不设置最大值( maxvalue/nomaxvalue:序列最大值/没有最大值)
NOCYCLE -- 一直累加,不循环
CACHE 10; --设置缓存cache个序列,如果系统down掉了或者其它情况将会导致序列不连续,也可以设置为---------NOCACHE

查看已有sequence

select * from user_sequences;
Select * from all_sequences;

从Sequence取值

select last_number from user_sequences where sequence_name='seqTest';
select seqTest.nextval from sys.dual; --注意每次查询都会自增

取当前值:

SELECT Sequence名称.CurrVal FROM DUAL;
例如:select seqtest.currval from dual;
sequence使用位置
不包含子查询、snapshot、VIEW的 SELECT 语句
INSERT语句的子查询中
INSERT语句的values中,例如insert into 表名(id,name)values(seqtest.Nextval,'sequence 插入测试');
UPDATE 的 SET中

alter sequence

拥有ALTER ANY SEQUENCE 权限才能改动sequence. 可以alter除start至以外的所有sequence参数.如果想要改变start值,必须 drop sequence 再 re-create。例:

alter sequence SEQTEST maxvalue 9999999;

另: SEQUENCE_CACHE_ENTRIES参数,设置能同时被cache的sequence数目。

drop sequence

DROP SEQUENCE seqTest;

案例

create sequence SEQ_ID
minvalue 1
maxvalue 99999999
start with 1
increment by 1
nocache
order;

---- 建解发器代码为:
create or replace trigger tri_test_id
  before insert on S_Depart   --S_Depart 是表名
  for each row
declare
  nextid number;
begin
  IF :new.DepartId IS NULLor :new.DepartId=0 THEN --DepartId是列名
    select SEQ_ID.nextval --SEQ_ID正是刚才创建的
    into nextid
    from sys.dual;
    :new.DepartId:=nextid;
  end if;
end tri_test_id;

----上面的代码就可以实现自动递增的功能了。
----或者
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 TABLE demo6
(
    id INT NOT NULL,
    key1 VARCHAR2(40) NULL,
    key2 VARCHAR2(40) NULL
);

设置主键

alter table demo6 add constraint demo6_pk primary key (id);

新建序列

create sequence demo6_id
minvalue 1
nomaxvalue 
increment by 1 
start with 1
nocache;

新建触发器

create or replace trigger demo6_tg_insertId
before insert on demo6 for each row 
begin
  select demo6_id.Nextval into:new.id from dual;
end;

插入数据

insert into demo6 (key1, key2)
values ('key1', 'key2');
insert into demo6 (key1, key2)
values ('key11', 'key22');

查询数据

--可以查看到刚才插入的2条数据
select * from demo6;

查询当前序列

select demo6_id.currval from dual;
-- 值是2

文章引自:https://www.cnblogs.com/shoshana-kong/p/8697131.html 文章引自:https://www.cnblogs.com/xiaostudy/p/10062491.html

登陆评论: 使用GITHUB登陆