• Oracle自增长ID


    在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.nextval, 'name1');
    insert into customers values(customer_id_seq.nextval, 'name2');
    select id from customers;

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

    通过触发器自动添加id字段

    从上述插入语句可以发现,如果每次都要插入customer_id_seq.nextval的值会非常累赘与麻烦,因此可以考虑使用触发器来完成这一步工作。

    创建触发器trg_customers

    create or replace
    trigger trg_customers before insert on customers for each row 
    begin 
    select CUSTOMER_ID_SEQ.nextval into :new.id from dual; 
    end;

    插入一条记录

    insert into customers(name) values('test'); 

    这是我们会发现这一条记录被插入到数据库中,并且id还是自增长的。

  • 相关阅读:
    PHP 超级全局变量
    PHP 魔术变量
    PHP 变量
    Thinkphp 模板中常用的系统变量总结
    PHP $GLOBALS超全局变量分析
    php使用curl的post提交数据和get获取网页数据的方法总结
    php获取客户端真实ip地址的三种方法
    Jquery 【on事件】
    ptyhon【递归练习】
    C#中的线程
  • 原文地址:https://www.cnblogs.com/colder/p/4651373.html
Copyright © 2020-2023  润新知