Oracle创建自增主键ID(序列+触发器)

根据需求创建了一张表,主要做插入操作,需要主键自增;把我的建表详情分享如下:

-- Create table
create table auto_incre
(
    auto_id NUMBER(10) not null,
    auto_des VARCHAR2(20),
    auto_sort  VARCHAR2(20)
)

tablespace CREDIT
    pctfree 10
    initrans 1
    maxtrans 255
    storage
    (
        initial 64K
        next 8K
        minextents 1
        maxextents unlimited
    );

 -- Add comments to the table
comment on table auto_incre
   is '主键自增表';
comment on column auto_incre.auto_id 
   is 'id,自增长主键';
comment on column auto_incre auto_des 
   is '描述';
comment on column auto_incre auto_sort 
   is '类别'; 


-- Create/Recreate primary,unique and foreign key constraints
alter table auto_incre
    add constraint PK_auto_incre primary key (auto_id)
    using index
    tablespace CREDIT
    pctfree 10
    initrans 2
    maxtrans 255
    storage
    (
        initial 64K
        next 1M
        minextents 1
        maxextents unlimited
    );

--Create sequence
create sequence seq_auto
increment by 1 -- 自增1
start with 1001 -- 从1001开始
nomaxvalue      -- 无最大值
minvalue 1001 ;  -- 最小值1001

--创建触发器将表与序列关联
create or replace trigger trg_auto
before insert on auto_incre for each row
    begin 
        select seq_auto.nextval into :new.auto_id from dual;
    end;

 触发器已启用

 执行插入语句

 ID已实现了自增长

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

触发器也不是必要的,建序列就可以了, 在编写Insert语句时,使用序列

 如上图所示seq_adv是序列名

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值