Oracle使用sequence(序列)+tirgger(觸發器)實現auto_increment(主鍵自增)
阿新 • • 發佈:2019-02-05
------------------------------------------------------------------------------------------------------
更新:20180619 由於觸發器不穩定且耗效能,這裡我寫了另一篇藉助序列NEXTVAL操作的實現方式
-------------------------------------------------------------------------------------------------------
受mysql的影響,在oracle建表的時候差點就控制不住自己的麒麟臂打下auto_increment。不過Oracle提供了一套機制也可以實現自增主鍵,雖然稍微麻煩點也算是殊途同歸。
資料準備-測試表:
create table hello(
hellokey varchar2(32),
anotherkey varchar2(16),
whatever varchar2(16),
primary key(hellokey, anotherkey)
);
實現步驟:
首先建立序列,注意你的資料庫使用者必須擁有建立序列的許可權。
create sequence testseq increment by 1 start with 1 maxvalue 3 --注意這裡只是為了看迴圈的效果而把最大值設定為3,正常情況應該根據需要設定為比較大的值比如9999999 cycle cache 2;
上面的語句,建立了一個名為testseq的序列,其引數含義依次為:
(這csdn真心是不會用。。。插表不能換行,強行插圖)
接下來建立觸發器
create or replace trigger my_trigger before insert on hello for each row declare tempkey hello.hellokey%type; --宣告臨時變數tempkey,hello.hellokey%type表示取hello表的hellokey的型別 begin select testseq.NEXTVAL into tempkey from dual; -- testseq.NEXTVAL 表示取序列testseq的下一個自增值 if :new.hellokey is null then -- :new表示要新插入的這一行 :new.hellokey := to_char(sysdate, 'yyyymmdd') ||'-'|| tempkey; --如果要插入的行中hellokey列為空,則生成一個"系統日期-自增值"形式的key end if; end;
這個觸發器會在我們每次插hello表時檢查hellokey欄位是否為空,若空就補充一個key值上去。
測試:
到這裡為止,我們就完成了序列+觸發器實現的主鍵自增,下面來測試下。
insert all
into hello(anotherkey, whatever) values('100','xxx')
into hello(anotherkey, whatever) values('101','xxx')
into hello(anotherkey, whatever) values('102','xxx')
into hello(anotherkey, whatever) values('103','xxx')
into hello(anotherkey, whatever) values('104','xxx')
select 1 from dual;
檢視hello表,可以看到:
最後,如果你建立好了觸發器,在插值的時候報錯 oracle trigger xxx is invalid and failed re-validation, 那是因為你寫的trigger編譯不通過導致的,檢查一下你是否存在語法錯誤,少了分號,括號,或者用錯函式都會導致編譯不過。
最後歡迎訪問個人部落格點選開啟連結