1.sequence+trigger enables Oracle column self-increment
CREATE SEQUENCE sequence Name
[INCREMENT by N]
[START with N]
[{Maxvalue/minvalue n| Nomaxvalue}]
[{cycle| Nocycle}]
[{CACHE n| NOCACHE}];
Create a test table
[Email protected] Cdb> CREATE TABLE TEST (
2 ID Number (Ten) is not NULL,
3 DESCRIPTION VARCHAR2 () not NULL,
4 CONSTRAINT test_pk PRIMARY KEY (ID)
5);
Table created.
elapsed:00:00:00.14
[Email protected] cdb> CREATE SEQUENCE test_seq;
Sequence created.
elapsed:00:00:00.02
elapsed:00:00:00.38
[Email protected] cdb> CREATE OR REPLACE TRIGGER Test_before_insert
2 before INSERT on test
3 for each ROW
4 BEGIN
5 SELECT Test_seq. Nextval INTO:new.id from dual;
6 END;
7/
Trigger created.
elapsed:00:00:00.12
[Email protected] Cdb> INSERT into TEST (DESCRIPTION) VALUES (' Do not specify ID ');
1 row created.
elapsed:00:00:00.08
[Email protected] Cdb> INSERT into TEST (ID, DESCRIPTION) VALUES (Test_user. Dept_seq. Nextval, ' specify ID ');
INSERT into TEST (ID, DESCRIPTION) VALUES (Test_user. Dept_seq. Nextval, ' Specify ID ')
*
ERROR at line 1:
Ora-02289:sequence does not exist
elapsed:00:00:00.01
[Email protected] Cdb> INSERT into TEST (ID, DESCRIPTION) VALUES (test_seq. Nextval, ' specify ID ');
1 row created.
elapsed:00:00:00.01
[Email protected] Cdb> SELECT * from TEST;
ID DESCRIPTION
1 不指定ID 3 指定ID
elapsed:00:00:00.03
2.DEFAULT Values Using Sequences
[Email protected] Cdb> INSERT into TEST (description) VALUES (' description only ');
1 row created.
elapsed:00:00:00.01
[Email protected] Cdb> INSERT into TEST (ID, description) VALUES (999, ' id=999 and description ');
1 row created.
elapsed:00:00:00.00
[Email protected] Cdb> INSERT into TEST (ID, description) VALUES (NULL, ' id=null and description ');
1 row created.
elapsed:00:00:00.01
[Email protected] Cdb> SELECT * from test;
ID DESCRIPTION
4 DESCRIPTION only 999 ID=999 and DESCRIPTION ID=NULL and DESCRIPTIONElapsed: 00:00:00.02
[Email protected] Cdb> CREATE TABLE TEST (
2 ID Number (Ten) DEFAULT on NULL test_seq. Nextval,
3 DESCRIPTION VARCHAR2 () not NULL
4);
Table created.
elapsed:00:00:00.02
[Email protected] Cdb> INSERT into TEST (description) VALUES (' description only ');
1 row created.
elapsed:00:00:00.01
[Email protected] Cdb> INSERT into TEST (ID, description) VALUES (999, ' id=999 and description ');
1 row created.
elapsed:00:00:00.01
[Email protected] Cdb> INSERT into TEST (ID, description) VALUES (NULL, ' id=null and description ');
1 row created.
elapsed:00:00:00.01
[Email protected] Cdb> SELECT * from test;
ID DESCRIPTION
5 DESCRIPTION only 999 ID=999 and DESCRIPTION 6 ID=NULL and DESCRIPTION
elapsed:00:00:00.02
3. Look at an article inside
Oracle column self-increment implementation