Oracle创建自增列的两种方式

Oracle含有序列的事务进行回滚,序列不会回到事务前状态。

复制-- 方法一: 序列
-- Created on 2023/3/10 by 112691 
declare 
  -- Local variables here
  v_cnt number;
begin
  -- Test statements here
  select count(*) into v_cnt from user_tables where table_name = upper('user_info');
  if v_cnt>0 then
    execute immediate 'drop table user_info';
    dbms_output.put_line('该表已删除');
  else
    execute immediate 'create table user_info(
                      id number(10) not null,
                      username varchar(20) not null,
                      constraints PK_USERINFO primary key(id)
                      )';
    dbms_output.put_line('该表已创建成功');
  end if;
end;

create sequence USER_INFO_SEQ
start with 1
minvalue 1
maxvalue 999999
increment by 1
-- cache: 申请序列时Oracle将序列提前生成cache x先存入内存。在发送大量的申请序列请求时,会优先去内存中取预存序列。但如果数据库重启时,预存内存中的序列值会被丢失,再次启动时候,预存重上次内存中最大序列号+1开始cache。	
cache 20; 

insert into user_info values(user_info_seq.nextval,'username1');
insert into user_info values(user_info_seq.nextval,'username2');
复制-- 方法二: 序列+触发器
create or replace trigger TIG_USER_INFO_INSERT
  before insert
  on user_info
  for each row
declare
  -- local variables here
begin
  select user_info_seq.nextval into :new.id from dual;
end TIG_USER_INFO_INSERT;

insert into user_info(username) values('username3');
commit;

drop table user_info ;
drop sequence USER_INFO_SEQ;

参考博客:
https://blog.csdn.net/qq_45554909/article/details/116912915
https://blog.csdn.net/fn0723/article/details/81104861

posted @   五字妹妹实在是棒  阅读(665)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
返回顶部
点击右上角即可分享
微信分享提示