oracle列自增实现

发布时间:2020-07-24 14:09:35 作者:whshurk
来源:网络 阅读:1691

1.Sequence+Trigger实现Oracle列自增
CREATE SEQUENCE 序列名
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE/MINVALUE n|NOMAXVALUE}]
[{CYCLE|NOCYCLE}]
[{CACHE n|NOCACHE}];
创建测试表
sys@newtestCDB> CREATE TABLE TEST(
2 ID NUMBER (10) NOT NULL,
3 DESCRIPTION VARCHAR2 (50) NOT NULL,
4 CONSTRAINT test_pk PRIMARY KEY (ID)
5 );

Table created.

Elapsed: 00:00:00.14
sys@newtestCDB> CREATE SEQUENCE test_seq;

Sequence created.

Elapsed: 00:00:00.02

Elapsed: 00:00:00.38
sys@newtestCDB> 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
sys@newtestCDB> INSERT INTO TEST (DESCRIPTION) VALUES ('不指定ID');

1 row created.

Elapsed: 00:00:00.08
sys@newtestCDB> INSERT INTO TEST (ID, DESCRIPTION) VALUES (TEST_USER.DEPT_SEQ.NEXTVAL, '指定ID');
INSERT INTO TEST (ID, DESCRIPTION) VALUES (TEST_USER.DEPT_SEQ.NEXTVAL, '指定ID')
*
ERROR at line 1:
ORA-02289: sequence does not exist

Elapsed: 00:00:00.01
sys@newtestCDB> INSERT INTO TEST (ID, DESCRIPTION) VALUES (TEST_SEQ.NEXTVAL, '指定ID');

1 row created.

Elapsed: 00:00:00.01
sys@newtestCDB> SELECT * FROM TEST;

    ID DESCRIPTION

     1 不指定ID
     3 指定ID

Elapsed: 00:00:00.03
2.DEFAULT Values Using Sequences
sys@newtestCDB> INSERT INTO TEST (description) VALUES ('DESCRIPTION only');

1 row created.

Elapsed: 00:00:00.01
sys@newtestCDB> INSERT INTO TEST (id, description) VALUES (999, 'ID=999 and DESCRIPTION');

1 row created.

Elapsed: 00:00:00.00
sys@newtestCDB> INSERT INTO TEST (id, description) VALUES (NULL, 'ID=NULL and DESCRIPTION');

1 row created.

Elapsed: 00:00:00.01
sys@newtestCDB> SELECT * FROM test;

    ID DESCRIPTION

     4 DESCRIPTION only
   999 ID=999 and DESCRIPTION
       ID=NULL and DESCRIPTION
Elapsed: 00:00:00.02

sys@newtestCDB> CREATE TABLE TEST(
2 ID NUMBER (10) DEFAULT ON NULL test_seq.NEXTVAL,
3 DESCRIPTION VARCHAR2 (50) NOT NULL
4 );

Table created.

Elapsed: 00:00:00.02
sys@newtestCDB> INSERT INTO TEST (description) VALUES ('DESCRIPTION only');

1 row created.

Elapsed: 00:00:00.01
sys@newtestCDB> INSERT INTO TEST (id, description) VALUES (999, 'ID=999 and DESCRIPTION');

1 row created.

Elapsed: 00:00:00.01
sys@newtestCDB> INSERT INTO TEST (id, description) VALUES (NULL, 'ID=NULL and DESCRIPTION');

1 row created.

Elapsed: 00:00:00.01
sys@newtestCDB> SELECT * FROM test;

    ID DESCRIPTION

     5 DESCRIPTION only
   999 ID=999 and DESCRIPTION
     6 ID=NULL and DESCRIPTION

Elapsed: 00:00:00.02
3.看上一篇里面

推荐阅读:
  1. Laravel中自增实现方案
  2. oracle创建固定长度的自增ID

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

自增长 自增实现 acle

上一篇:FreeNas搭建踩坑指南(二)

下一篇:nagios参数详解

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》