建立主鍵自增表
阿新 • • 發佈:2018-11-19
MySQL
在建表的時候宣告欄位即可
id int auto_increment primary key not null
Oracle
第一步:建立表
drop table t_role;
create table t_role (
role_name varchar(255) NOT NULL,
note varchar(255) NOT NULL,
id number NOT NULL,
PRIMARY KEY (id)
);
這裡需要注意主鍵id得是number型別的,如果是int型別將無法觸發觸發器。
第二步:建立序列
create sequence role_sequence minvalue 1 --最小值 nomaxvalue --不設定最大值(由機器決定),或 根據表字段的值範圍設定 maxvalue maxvalue 99999999 -- 最大值 start with 1 --從1開始計數,數值可變 increment by 1 --每次加1,數值可變 nocycle --一直累加,不迴圈 nocache; --不建緩衝區。 如果建立cache那麼系統將自動讀取cache值個seq,這樣會加快執行速度;如果在單機中使用cache,或者oracle死了,那麼下次讀取的seq值將不連貫,所以不建議使用cache。 create sequence role_sequence minvalue 1 nomaxvalue start with 1 increment by 1 nocycle nocache;
第三步:建立觸發器執行
create or replace trigger role_trig
before
insert on t_role for each row when (new.id is null)
BEGIN
select role_sequence.nextval into :new.id from dual;
END;
/
測試一下:
insert into t_role(note,role_name) values('連線','nihao'); insert into t_role(note,role_name) values('連線','nihao'); insert into t_role(note,role_name) values('連線','nihao'); commit;