zoukankan      html  css  js  c++  java
  • MySQL,Oracle建立主键自增表

    MySQL

    在建表的时候声明字段即可

    id int auto_increment primary key not null

    Oracle

    第一步:建立表

    drop table t_role;
    create table t_role (
      role_name varchar(255) NOT NULL,
      note varchar(255) NOT NULL,
      id number NOT NULL,
      PRIMARY KEY (id)
    );
    

    这里需要注意主键id得是number类型的,如果是int类型将无法触发触发器。

    第二步:建立序列

     create sequence role_sequence
     minvalue 1  --最小值
     nomaxvalue  --不设置最大值(由机器决定),或 根据表字段的值范围设置 maxvalue
     maxvalue 99999999  -- 最大值
     start with 1   --从1开始计数,数值可变
     increment by 1  --每次加1,数值可变
     nocycle  --一直累加,不循环
     nocache;  --不建缓冲区。      如果建立cache那么系统将自动读取cache值个seq,这样会加快运行速度;如果在单机中使用cache,或者oracle死了,那么下次读取的seq值将不连贯,所以不建议使用cache。
     create sequence role_sequence
     minvalue 1 
     nomaxvalue  
     start with 1   
     increment by 1  
     nocycle  
     nocache;  
    

    第三步:建立触发器执行

    create or replace trigger role_trig 
    before
    insert on t_role for each row when (new.id is null)
    BEGIN
    select role_sequence.nextval into :new.id from dual;
    END;
    /
    

    测试一下:

    insert into t_role(note,role_name) values('连接','nihao');
    insert into t_role(note,role_name) values('连接','nihao');
    insert into t_role(note,role_name) values('连接','nihao');
    commit;
    
  • 相关阅读:
    js实现输入银行卡号隔四位添加一个空格
    写出优雅的代码
    FOJ Problem 1016 无归之室
    FOJ Problem 1015 土地划分
    大数相加减
    NYOJ 42 一笔画
    NYOJ36 水池数目
    NYOJ 32 组合数
    贪吃蛇StringBuilder 和 定时器
    星 辰 · 第 三 条 约 定
  • 原文地址:https://www.cnblogs.com/bihanghang/p/9983798.html
Copyright © 2011-2022 走看看