Oracle列自增实现(3)-DEFAULT Values Using Sequences
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)
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。