oracle建表設置自增主鍵

oracle建表設置自增主鍵

--建表

create table t_student

( s_id     number primary key,

 name    char(10) not null

);


--建序列

create sequence stu_sequence

increment by 1

start with 1

nomaxvalue

nocycle

cache 10;


-- 建觸發器

create or replace trigger stu_trigger    
before insert on t_student                 
for each row
declare
nextid number;
begin
IF:new.s_id IS NULL or:new.s_id=0 THEN                
select stu_sequence.nextval                                             
into nextid
from sys.dual;
:new.s_id:=nextid;
end if;
end stu_trigger; 


注:stu_trigger爲觸發器名

     t_student爲表名

     s_id爲自增長的主鍵字段名


這樣就可以了,插入數據測試:

插一條數據:

insert into t_student (name) values('張三');

插多條數據:

BEGIN 

FOR v_i IN 1..10 Loop

INSERT INTO t_student (name) VALUES ('鄭成');

END Loop;

COMMIT;

END;

只插主鍵值:

INSERT INTO t_student(s_id) VALUES (stu_sequence.nextval);




發佈了30 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章