Oracle创建表:id自增长

oracle创建主键自增长表需要三个步骤:

创建表

CREATE TABLE STUDENT(
  ID NUMBER NOT NULL,
  NAME VARCHAR2(4000) NOT NULL,
  PRIMARY KEY(ID)
)

创建序列

CREATE SEQUENCE SEQUENCE_STUDENT_ID MINVALUE 1 NOMAXVALUE INCREMENT BY 1 START WITH 1 NOCACHE;

创建触发器

CREATE OR REPLACE TRIGGER TRG_ON_INS_STUDENT BEFORE INSERT ON STUDENT FOR EACH ROW WHEN(NEW.ID IS NULL)
BEGIN
  SELECT SEQUENCE_STUDENT_ID.NEXTVAL INTO :NEW.ID FROM DUAL;
END;

验证:插入数据

INSERT INTO STUDENT(name) values ('Dauting');

你可能感兴趣的:(数据库)