码迷,mamicode.com
首页 > 数据库 > 详细

Oracle列自增实现(3)-DEFAULT Values Using Sequences

时间:2015-04-25 06:51:32      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/xqzt/p/4455171.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!