Oracle設定主鍵自增 最詳細最全

2021-09-24 22:39:33 字數 2277 閱讀 8658

--drop table test_trigger; 

create table test_trigger( --建立表及其字段

test_id number(20) not null,

trigger_detail varchar2(500) not null,

trigger_des varchar2(10),

user_id varchar2(10),

create_date date,

constraint guide_pk primary key (test_id)); --設定表約束名(guide_pk),設定主鍵為test_id

--//建立名字為guide_seqtest的 序列, oracle沒有自增主鍵,需要通過建立序列才能實現自增

create sequence guide_seqtest --建立序列的名稱-->guide_seqtest

minvalue 1       --最小值

nomaxvalue       --不設定最大值

start with 1     --從1開始計數

increment by 1   --每次加1

nocycle          --一直累加,不迴圈

nocache;         --不建緩衝區  nocache  或者設定快取 cache n  /--其中n代表乙個整數,預設值為20

--如果指定cache值,oracle就可以預先在記憶體裡面放置一些sequence,

--這樣訪問的快些。cache裡面的取完後,oracle自動再取一組到cache。

--使用cache或許會跳號, 比如資料庫突然不正常down掉(shutdown abort),cache中的sequence就會丟失。

--舉個例子:比如你的sequence中cache 100,那當你sequence取到90時突然斷電,那麼在你重啟資料庫後,sequence的值將從101開始。

-- 建觸發器,新增時觸發

create or replace trigger guide_trigger --  guide_trigger 觸發器名稱

before insert on test_trigger for each row -- test_trigger 表名

begin

select guide_seqtest.nextval into :new.test_id from dual;  

end;

--使用guide_seqtest.nextval,方式來獲取序列 其中guide_seqtest是上面建立序列的名稱,.nextval是獲取序列值的方法

-- new.需要自增的主鍵名,new.test_id 其中test_id 就是上面建表的主鍵名

--//下面我們插入幾組資料實驗

insert into test_trigger( trigger_detail, trigger_des, user_id, create_date) values('0034','393040','zl',sysdate);

insert into test_trigger( trigger_detail, trigger_des, user_id, create_date) values('0035','393040','zzl',sysdate);

insert into test_trigger( trigger_detail, trigger_des, user_id, create_date) values('00316','393040','z45l',sysdate);

insert into test_trigger( trigger_detail, trigger_des, user_id, create_date) values('00137','393040','z3l',sysdate);

insert into test_trigger( trigger_detail, trigger_des, user_id, create_date) values('00134','393040','3zzzl',sysdate);

insert into test_trigger( trigger_detail, trigger_des, user_id, create_date) values('00130','393040','zzz8765zl',sysdate);

commit;

//在沒有報錯的情況下,查詢資料是否存在

select  * from test_trigger

設定Oracle主鍵自增

oracle沒有設定主鍵auto increment的功能,需要自己編寫序列和觸發器實現主鍵自動遞增。示例 建立表menu create table menu menuid number 10 not null primary key,name varchar2 40 not null,id par...

oracle設定主鍵自增

oracle中沒有自增字段,可通過序列 觸發器間接實現,cmd中sqlplus登入,直接執行即可。一般要經過一下幾步 1建立資料表 code create table test increase userid number 10 primary key,主鍵,自動增加 username varcha...

oracle中設定自增主鍵

新建序列 create sequence name increment by x x為增長間隔 start with x x為初始值 maxvalue x x為最大值 nomaxvalue 不設定最大值 minvalue x x為最小值 nominvalue 不設定最小值 cycle 迴圈使用,到達...