• ORACLE数据库实现自增的两种方式


    Mysql数据库因为其有自动+1,故一般我们不需要花费太多时间,直接用关键字auto_increment即可,但是Oracle不行,它没有自动增长机制。顾我们需要自己去实现。一般有两种方式,但是这两种方式都与序列化有关。第一种方式:序列化+触发器;第二种方式:序列化+显示调用序列化。一般我选用第一种方式。因为我们只要建立好序列化+触发器,这样我们就需要太多的去关注这个字段了,触发器会在我们插入数据时自动触发,帮助我们进行+1操作。这正好解决了我最近做的一个mini项目中的部门删除操作(子部门与父部门),因为我们知道父部门总是先于子部门存在于数据库中,如果我们额外建一个字段去记录插入数据的先后顺序,这样我们在做删除时,只要让子部门先于父部门删除,这样就不会存在因为批量删除部门,因删除父部门递归删除子部门,再删子部门时发现没有子部门的存在了而报异常。好了案例说完了。现在来在oracle数据库中具体实现自增1的操作。

    准备工作建表:

    //准备工作创建一张表
    create table dept_p(
    	dept_id   VARCHAR2(40) not null,
      	dept_name VARCHAR2(40),
     	parent_id VARCHAR2(40),
      	state     NUMBER(11),
      	dept_sort NUMBER(11)
    );
    alter table DEPT_P add [constraint dept_id] primary key(dept_id);
    

    方式一:序列化+触发器

    第一步:创建序列sequence

    create sequence seq_t_dept
    minvalue 1
    maxvalue 99999999
    start with 1
    increment by 1
    cache 50
    

    第二步:建立触发器

    create or replace trigger "dept_trig"
    	before insert on dept_p
    	referencing old as old new as new for each row
    declare
    begin
    	select seq_t_dept.nextval into :new.dept_sort from dual;
    end dept_trig;
    

    第三步:插入数据测试看dept_sort是否自增

    insert into dept_p values('001', '安保部', '000', 1);
    select * from dept_p;
    

    方式二:序列化+显示调用

    第一步:创建序列sequence

    //创建sequence
    create sequence seq_on_dept
    increment by 1
    start with 1
    nomaxvalue
    nocycle
    nocache;
    

    第二步:显示调用序列

    insert into dept_p values('001', '安保部', '000', 1, seq_on_test.nextval);
    

    第三步:查询进行查看 

    select * from dept_p
    

    注:

    //查看序列当前值和下一个值的查看方式
    select seq_on_dept.currval from dual;
    select seq_on_dept.nextval from dual; 
    

    总结:

    create sequence 序列名
    [increment by n] 
    [start with n]
    [{maxvalue/minvalue n | nomaxvalue}] 
    [{cycle|nocycle}]
    [{cache n | nocache}];
    

     

  • 相关阅读:
    【uiautomator】Interfaces+Exception
    【uiautomator】UiDevice
    【uiautomator】Uiautomator API
    【uiautomator】运行命令
    [www.infoshare.cc]【uiautomator】输入中文(输入法安装+测试代码)
    MFC ,List使用
    VC控件DateTimePicker使用方法
    GitHub vs. Bitbucket 不只是功能不同
    免费的私人代码托管(bitbucket) 和 常用git指令
    修改android studio中的avd sdk路径、avd sdk找不到的解决方案
  • 原文地址:https://www.cnblogs.com/lgx5/p/11508649.html
Copyright © 2020-2023  润新知