zoukankan      html  css  js  c++  java
  • 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;

    clip_image001

    二、默认值明确为非空

    创建两个序列

    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;

    clip_image002

    三、例子:主从表的简单例子

    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;

    clip_image003

    SELECT * FROM detail;

    clip_image004

    原文:

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

  • 相关阅读:
    flask 基础
    新的项目部署
    linux (01) linux基础
    linux (04) linux安装mysql
    linux (06) redis安装
    linux (09) nginx反向代理,负载均衡
    linux (08) nginx入门详解
    linux (07) redis详解
    linux(05) 编译安装py3
    spring-boot war包部署(二)
  • 原文地址:https://www.cnblogs.com/xqzt/p/4455171.html
Copyright © 2011-2022 走看看