Oracle achieved in several ways from the growing primary key

As the core of a database system, 1NF table structure is a database design must have a unique primary key constraint is, Oracle database itself is not self-growth mechanism, unlike MySQL directly using a keyword AUTO_INCREMENT automatic, so we need to do it yourself , here are several ways to achieve

A sequence of flip-+

The first step to create a sequence in the case of the complete structure of the table

CREATE SEQUENCE SEQ_NAME
    INCREMENT BY 1
    MINVALUE 1
    MAXVALUE 9999999999999999
    START WITH 1
    CACHE 20

The second part to create a trigger

CREATE OR REPLACE TRIGGER TRIGGER_NEW
BEFORE INSERT ON TABLE_NAME
REFERENCING OLD AS "OLD" NEW AS "NEW" FOR EACH ROW
ENABLE WHEN (NEW.ID IS NULL)
BEGIN 
    SELECT 
        SEQ_NEW INTO : NEW.ID
    FROM 
         DUAL
END

Second, to show the call sequence +

Also create a trigger 

CREATE SEQUENCE SEQ_NAME
    INCREMENT BY 1
    MINVALUE 1
    NOMAXVALUE
    START WITH 1
    NOCYCLE
    NOCACHE

The following shows the call

INSERT INTO TABLE_NAME VALUES(SEQ_NAME.NEXTVAL)

Third, specify a primary key, query this table plus a maximum of one

INSERT INTO TABLE_NAME VALUES(SELECT MAX(ID)+1 ID FROM TABLE_NAME2)

Of course, a third way great limitations, can be operated without SQL statements in the code to accumulate, because the execution speed of the code is far more sql statement in code execution speed much more quickly

Note:

View the current value of the sequence

SELECT SEQ_NAME.CURRVAL FROM DUAL

View the current value of the next sequence

SELECT SEQ_NAME.NEXTVAL FROM DUAL

dual for Oracle inside a virtual table, was not real

 

Guess you like

Origin www.cnblogs.com/LiuFqiang/p/11826659.html