oracle中設定自增主鍵

2021-04-13 06:43:40 字數 2419 閱讀 8387

新建序列

create   sequence   name     

increment   by   x   //x為增長間隔     

start   with     x   //x為初始值     

maxvalue         x   //x為最大值   nomaxvalue    不設定最大值

minvalue         x   //x為最小值     nominvalue   不設定最小值

cycle                //迴圈使用,到達最大值或者最小值時,從新建立物件 (從頭開始,也可以為nocycle)

cache            x   //制定快取序列值的個數   

刪除序列drop sequence 序列名

如果指定cache值,oracle就可以預先在記憶體裡面放置一些       sequence,這樣訪問的快些。cache裡面的取完後,oracle自動再取一組到cache。 使用cache或許會跳號, 比如資料庫突然不正常down掉(shutdown abort),cache中的sequence就會丟失. 所以可以在create sequence的時候用nocache防止這種情況。

但是要注意的是:第一次nextval返回的是初始值;隨後的nextval會自動增加你定義的increment by值,然後返回增加後的值。currval總是返回當前sequence的值,但是在第一次nextval初始化之後才能使用currval,否則會出錯。

------------------------乙個例子-----------------------

create   sequence   for_test  --序列名     

increment   by   1     --每次增加1

start   with   1     --從1開始

nomaxvalue     --沒有最大值

nocache        --沒有快取序列

----------------------------建立測試表------------------

create table test

(testid int primary key,

testname varchar2(20) not null,

tdescription varchar2(200) null

)-----------------------------使用序列-------------------

insert into test

values(for_test.nextval,'序列測試','這是乙個序列使用的例子')

--------------------序列使用結果查詢-----------------

select * from test

觸發器

1

create or replace trigger "觸發器名稱" before

insert on test for each row when (new.testid is null)

begin

select for_test.nextval into: new.testid from dual;  //for_test  序列名 

end;

insert into test (testname,tdescription ) values('cao','heibei');

刪除觸發器drop trigger 觸發器名稱

2

create or replace trigger trigger_name

before insert on your_sid.tablename

for each row

begin

declare

i number;

cursor cur is select max(id) from your_sid.tablename;

begin

open cur;

fetch cur into i;

if i is null then

:new.id := 0;  //可以根據實際需要來定初始值

else

:new.id := i + 1; //這裡以1遞增

end if;

close cur;

end;

end;

/其中:your_sid為資料庫的當前使用者sid,tablename為表名,id為列名

序列提供兩個方法,nextval和currval。顧名思義,nextval為取序列的下乙個值,一次nextval會增加一次sequence的值;currval為取序列的當前值。  

oracle中自增主鍵設定

mysql中主鍵自增設置為auto increment屬性,oracle中沒有該屬性,而是通過sequence序列,間接來實現主鍵自增功能 參考 序列 sequence 又叫序列生成器,用於提供一系列的數字,開發人員使用序列生成唯一鍵。每次訪問序列,序列按照一定的規律增加或者減少.序列建立引數說明 ...

設定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...