Mysql數據庫因為其有自動+1,故一般我們不需要花費太多時間,直接用關鍵字auto_increment即可,但是Oracle不行,它沒有自動增長機制。顧我們需要自己去實現。一般有兩種方式,但是這兩種方式都與序列化有關。第一種方式:序列化+觸發器;第二種方式:序列化+顯示調用序列化。一般我選用第一種方式。因為我們只要建立好序列化+觸發器,這樣我們就需要太多的去關注這個字段了,觸發器會在我們插入數據時自動觸發,幫助我們進行+1操作。這正好解決了我最近做的一個mini項目中的部門刪除操作(子部門與父部門),因為我們知道父部門總是先於子部門存在於數據庫中,如果我們額外建一個字段去記錄插入數據的先后順序,這樣我們在做刪除時,只要讓子部門先於父部門刪除,這樣就不會存在因為批量刪除部門,因刪除父部門遞歸刪除子部門,再刪子部門時發現沒有子部門的存在了而報異常。好了案例說完了。現在來在oracle數據庫中具體實現自增1的操作。
准備工作建表:
//准備工作創建一張表 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);
方式一:序列化+觸發器
第一步:創建序列sequence
create sequence seq_t_dept minvalue 1 maxvalue 99999999 start with 1 increment by 1 cache 50
第二步:建立觸發器
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;
第三步:插入數據測試看dept_sort是否自增
insert into dept_p values('001', '安保部', '000', 1); select * from dept_p;
方式二:序列化+顯示調用
第一步:創建序列sequence
//創建sequence create sequence seq_on_dept increment by 1 start with 1 nomaxvalue nocycle nocache;
第二步:顯示調用序列
insert into dept_p values('001', '安保部', '000', 1, seq_on_test.nextval);
第三步:查詢進行查看
select * from dept_p
注:
//查看序列當前值和下一個值的查看方式 select seq_on_dept.currval from dual; select seq_on_dept.nextval from dual;
總結:
create sequence 序列名 [increment by n] [start with n] [{maxvalue/minvalue n | nomaxvalue}] [{cycle|nocycle}] [{cache n | nocache}];