Oracle列自增實現(3)-DEFAULT Values Using Sequences

來源:互聯網
上載者:User

標籤:

Oracle 12c中,可以使用序列的NEXTVAL and CURRVAL的值作為預設值,來實現列自增!

一、使用序列的 NEXTVAL and CURRVAL 的值作為預設值

建立序列

CREATE SEQUENCE t1_seq;

建表

CREATE TABLE t1 ( id NUMBER DEFAULT t1_seq.NEXTVAL, description VARCHAR2(30) );

插入資料

INSERT INTO t1 (description) VALUES (‘DESCRIPTION only‘);INSERT INTO t1 (id, description) VALUES (999, ‘ID=999 and DESCRIPTION‘);INSERT INTO t1 (id, description) VALUES (NULL, ‘ID=NULL and DESCRIPTION‘);

查詢結果

SELECT * FROM t1;

二、預設值明確為非空

建立兩個序列

CREATE SEQUENCE default_seq;CREATE SEQUENCE default_on_null_seq;

建表,col1和col2分別使用上面兩個序列的NEXTVAL作為預設值,其中col2 DEFAULT ON NULL

CREATE TABLE t2 (col1 NUMBER DEFAULT default_seq.NEXTVAL,col2 NUMBER DEFAULT ON NULL default_on_null_seq.NEXTVAL,description VARCHAR2(30));

插入資料

INSERT INTO t2 (description) VALUES (‘DESCRIPTION only‘);INSERT INTO t2 (col1, col2, description) VALUES (999, 999, ‘999,999,DESCRIPTION‘);INSERT INTO t2 (col1, col2, description) VALUES (NULL, NULL, ‘NULL,NULL,DESCRIPTION‘);

查詢資料,可以看到col2位NULL時候,被預設轉換使用了default_on_null_seq.NEXTVAL的

SELECT * FROM t2;

三、例子:主從表的簡單例子

CREATE SEQUENCE master_seq;

CREATE SEQUENCE detail_seq;

CREATE TABLE master (

id NUMBER DEFAULT master_seq.NEXTVAL,

description VARCHAR2(30)

);

CREATE TABLE detail (

id NUMBER DEFAULT detail_seq.NEXTVAL,

master_id NUMBER DEFAULT master_seq.CURRVAL,

description VARCHAR2(30)

);

INSERT INTO master (description) VALUES (‘Master 1‘);

INSERT INTO detail (description) VALUES (‘Detail 1‘);

INSERT INTO detail (description) VALUES (‘Detail 2‘);

INSERT INTO master (description) VALUES (‘Master 2‘);

INSERT INTO detail (description) VALUES (‘Detail 3‘);

INSERT INTO detail (description) VALUES (‘Detail 4‘);

SELECT * FROM master;

SELECT * FROM detail;

原文:

DEFAULT Values for Table Columns : Enhancements in Oracle Database 12c Release 1 (12.1)

Oracle列自增實現(3)-DEFAULT Values Using Sequences

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.