1. 程式人生 > >oracle 11g及以下的版本定義自增主鍵

oracle 11g及以下的版本定義自增主鍵

11g及以下的版本定義自增主鍵(更高版本可以直接定義autoincreatement 的主鍵)

CREATE TABLE collect (
  ID           NUMBER(10)   PRIMARY KEY NOT NULL,
 mobile VARCHAR2(50),
 something_else VARCHAR2(50)
 );

CREATE SEQUENCE collect_seq START WITH 1;


CREATE OR REPLACE TRIGGER tr_collect_id
BEFORE INSERT
ON collect
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN
  if(:new.id is null) then
  SELECT collect_seq.nextval
  INTO :new.id
  FROM dual;
  end if;
END;
/
ALTER TRIGGER tr_collect_id ENABLE;