• oracle 主键应用序列和触发器实现自动增长


    oracle 主键自动增长  

     

    这几天搞Oracle,想让表的主键实现自动增长,查网络实现如下:

    create table simon_example

    (

      id number(4) not null primary key,

      name varchar2(25)

    )

    -- 建立序列:

    -- Create sequence

    create sequence SIMON_SEQUENCE                      

    minvalue 1              

    maxvalue 999999999999999999999999999 

    start with 1

    increment by 1

    cache 20;

    -- 建立触发器

    create trigger "simon_trigger" before

    insert on simon_example for each row when(new.id is null)

    begin

     select simon_sequence.nextval into:new.id from dual;

     end;

    -------------------------------------------------------------------------

    2、从序列中获取自动增长的标识符

    在Oracle中,可以为每张表的主键创建一个单独的序列,然后从这个序列中获取自动增加的标识符,把它赋值给主键。例如一下语句创建了一个名为customer_id_seq的序列,这个序列的起始值为1,增量为2。

    create sequence customer_id_seq increment by 2 start with 1

    一旦定义了customer_id_seq序列,就可以访问序列的curval和nextval属性。

    curval:返回序列的当前值

    nextval:先增加序列的值,然后返回序列值

    以下sql语句先创建了customers表,然后插入两条记录,在插入时设定了id和name字段的值,其中id字段的值来自于customer_id_seq序列。最后查询customers表中的id字段。

    create table customers(id int primary key not null, name varchar(15));

    insert into customers values(customer_id_seq.curval, "name1"),(customer_id_seq.nextval, "name2");

    select id from customers;

    如果在oracle中执行以上语句,查询结果为:

    id

    1

    3

    ----------------------------------------------------------------

    比如我现在创建一个表:student

    create table STUDENT
    (
    ID NUMBER not null,
    NAME VARCHAR2(20) default '男',
    SEX VARCHAR2(4),
    ADDRESS VARCHAR2(40),
    MEMO VARCHAR2(60)
    )

    现在我想实现每插入一条数据,就让id自动增长1.在SQLSERVER中这个很好实现,但在oracle中我搞了半天,查了下资料发现要用到“序列(sequence)”,“触发器”的知识。

    首先,创建一个序列:

    create sequence STU
    minvalue 1
    maxvalue 999999999999
    start with 21
    increment by 1
    cache 20;

    然后,给表student创建一个触发器:

    create or replace trigger stu_tr
    before insert on student 
    for each row
    declare
    -- local variables here
    begin
    select stu.nextval into :new.id from dual;
    end stu_tr;

  • 相关阅读:
    20000字干货笔记,一天搞定Mysql~【转】
    Linux操作系统概述及内核介绍
    如何在装有高版本NBU的主机上安装低版本的NBU?卸载8.0安装7.5记录
    vmware+kvm+vnc安装配置
    NBU异机恢复Oracle数据库,作业报错2850处理
    NetBackup 进程整理
    1、虚拟化实施流程、宿主机如何选型、如何进行性能测试
    灾难恢复的衡量指标RTO和RPO
    国内主要灾备厂商
    单例设计模式
  • 原文地址:https://www.cnblogs.com/nidakun/p/3860079.html
Copyright © 2020-2023  润新知