oracle自增的两种办法,ORACLE数据库实现自增的两种方式
Mysql數(shù)據(jù)庫因?yàn)槠溆凶詣?#43;1,故一般我們不需要花費(fèi)太多時間,直接用關(guān)鍵字auto_increment即可,但是Oracle不行,它沒有自動增長機(jī)制。顧我們需要自己去實(shí)現(xiàn)。一般有兩種方式,但是這兩種方式都與序列化有關(guān)。第一種方式:序列化+觸發(fā)器;第二種方式:序列化+顯示調(diào)用序列化。一般我選用第一種方式。因?yàn)槲覀冎灰⒑眯蛄谢?#43;觸發(fā)器,這樣我們就需要太多的去關(guān)注這個字段了,觸發(fā)器會在我們插入數(shù)據(jù)時自動觸發(fā),幫助我們進(jìn)行+1操作。這正好解決了我最近做的一個mini項(xiàng)目中的部門刪除操作(子部門與父部門),因?yàn)槲覀冎栏覆块T總是先于子部門存在于數(shù)據(jù)庫中,如果我們額外建一個字段去記錄插入數(shù)據(jù)的先后順序,這樣我們在做刪除時,只要讓子部門先于父部門刪除,這樣就不會存在因?yàn)榕縿h除部門,因刪除父部門遞歸刪除子部門,再刪子部門時發(fā)現(xiàn)沒有子部門的存在了而報異常。好了案例說完了。現(xiàn)在來在oracle數(shù)據(jù)庫中具體實(shí)現(xiàn)自增1的操作。
準(zhǔn)備工作建表:
//準(zhǔn)備工作創(chuàng)建一張表
create table dept_p(
dept_id VARCHAR2(40) not null,
dept_name VARCHAR2(40),
parent_id VARCHAR2(40),
state NUMBER(11),
dept_sort NUMBER(11)
);
alter table DEPT_P add [constraint dept_id] primary key(dept_id);
方式一:序列化+觸發(fā)器
第一步:創(chuàng)建序列sequence
create sequence seq_t_dept
minvalue 1
maxvalue 99999999
start with 1
increment by 1
cache 50
第二步:建立觸發(fā)器
create or replace trigger "dept_trig"
before insert on dept_p
referencing old as old new as new for each row
declare
begin
select seq_t_dept.nextval into :new.dept_sort from dual;
end dept_trig;
第三步:插入數(shù)據(jù)測試看dept_sort是否自增
insert into dept_p values('001', '安保部', '000', 1);
select * from dept_p;
方式二:序列化+顯示調(diào)用
第一步:創(chuàng)建序列sequence
//創(chuàng)建sequence
create sequence seq_on_dept
increment by 1
start with 1
nomaxvalue
nocycle
nocache;
第二步:顯示調(diào)用序列
insert into dept_p values('001', '安保部', '000', 1, seq_on_test.nextval);
第三步:查詢進(jìn)行查看
select * from dept_p
注:
//查看序列當(dāng)前值和下一個值的查看方式
select seq_on_dept.currval from dual;
select seq_on_dept.nextval from dual;
總結(jié):
create sequence 序列名
[increment by n]
[start with n]
[{maxvalue/minvalue n | nomaxvalue}]
[{cycle|nocycle}]
[{cache n | nocache}];
標(biāo)簽:自增,seq,sequence,數(shù)據(jù)庫,dept,部門,ORACLE,序列化,select
來源: https://www.cnblogs.com/lgx5/p/11508649.html
總結(jié)
以上是生活随笔為你收集整理的oracle自增的两种办法,ORACLE数据库实现自增的两种方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: native react 变颜色 点击_
- 下一篇: linux cmake编译源码,linu