Oracle建立表並實現主鍵自增

2021-09-26 23:20:12 字數 2048 閱讀 2071

create table user (

id number(10) primary key,

uname varchar2(50) not null,

pwd varchar2(32),

tel varchar2(11),

email varchar2(50)

);

create sequence user_seq

increment by 1

start with 1

nomaxvalue

nocycle

nocache;

increment by 1         每次增加幾

start with 1               從1開始

nomaxvalue               不設定最大值

nocycle                      累加不迴圈

cache n / nocache   緩衝區,其中n代表乙個整數,預設值為20,nocache就是代表不建緩衝區

如果設定了緩衝區,在主流的關係型資料庫中就可以預先在記憶體裡面放置一些sequence,來加快訪問速度。簡單來說,緩衝(或者快取)裡沒有資料,那麼它會先去資料庫裡找最大值,讀取出來後再+1,從磁碟的讀取速度要比從記憶體中讀取慢很多了。但如果設定了緩衝,裡面的取完後,oracle自動再取一組到緩衝區中。看到這裡有人就會想問為什麼要不設定緩衝區。原因是 因為,使用緩衝區或許會跳號, 比如資料庫突然不正常down掉,而之前緩衝區從序列裡那出來的資料在序列裡已經存在了,而重啟資料庫後緩衝區的資料就丟失了,oracle再重新從資料庫中拿最大值,但前面的就空掉了,舉個例子,你去小賣部買雪糕,先記賬不給錢,你買了10根,放到冰箱裡,但家裡停電了,雪糕全化掉,你決定去小賣部再買10根,老闆計數就從11開始了,雖然你一根都沒吃,但對於老闆來說,視為你已經吃了。

到這裡其實就已經可以實現自增了,sql語句是

insert into user(

id,uname,

pwd,

tel,

email

)values(

user_seq.nextval,

'test',

'123456',

'13801231234',

'test@***.com'

);

user_seq.nextval從序列裡那到自增的值

create trigger user_seq

before insert on user

for each row

when (new.id is null)

begin

select user_seq.nextval into:new.id from sys.dual;

end;

before:表示在資料庫動作之前觸發器執行;

insert :資料庫插入會觸發此觸發器;

for each row:對錶的每一行觸發器執行一次。如果沒有這一選項,則只對整個表執行一次。

when (new.id is null)

begin

select user_seq.nextval into:new.id from sys.dual;

end;

上邊這一段就是條件,新的資料id是空的,就去序列裡找到下乙個值放到新的資料id裡

下面這句sql和上面的區別就是,不用管id列,通過觸發器(insert)他自己去找到資料填充進去了

insert into user(

uname,

pwd,

tel,

email

)values(

'test',

'123456',

'13801231234',

'test@***.com'

);

sys.dual是乙個表,這裡不詳細介紹了,想看的朋友移步oracle資料庫裡dual表是什麼表?

Oracle建立主鍵並實現自增

1 建立資料庫表 設定主鍵 create table users userid number 10 primary key,主鍵,not null username varchar2 20 附 刪除表 drop table users 2 建立序列自增 create sequence user se...

Oracle 建立表並設定主鍵自增

建立資料庫 create table student id number primary key,name varchar 200 not null,varchar 200 create date date 指定表名注釋 comment on table student is 學生表 指定列注釋 c...

oracle建立表並新增主鍵,設定主鍵自增長

oracle序列詳解和建立自增主鍵 oracle序列主鍵 序列 是oacle提供的用於產生一系列唯一數字的資料庫物件。l 自動提供唯一的數值 l 共享物件 l 主要用於提供主鍵值 l 將序列值裝入記憶體可以提高訪問效率 1.首先建立序列,oracle序列的語法格式為 create sequence ...