网站首页 > 技术文章 正文
众所周知,Oracle是没有办法像Mysql里用AUTO_INCREMENT实现自增的。
但是Oracle可以通过序列实现自增。
--以下是oracle 12c的方法
create sequence temp_seq
increment by 1
start with 1001;
--创建一个简单的序列
create table temp(
id number default temp_seq.nextval primary key,
name varchar2(20)
);
--创建一个表
insert into temp(name) values('测试');
insert into temp(name) values('测试');
select * from temp;
但是这里有一个小问题,就是如果已存在该id,插入会报错,因为序列是一个跟表无关的对象。不会检查id,当id存在时,序列不会继续自动跳到下一个值。
如上图,当表已存在行id = 1005时,序列增加到1005时会违反主键约束,那么有没有一种可能,可以让这个序列跳到1006呢?
还得是触发器啊。
create sequence test_seq
increment by 1
start with 1001;
--用触发器获取此序列的值
create table test(
id number default '0' primary key,
name varchar2(20)
);
--这里默认值设为0是判断使不使用序列
--当不使用序列时的插入是Insert into test (id,name) values('1234','测试');
--当使用序列时的插入是insert into test (name) values('测试');
create or replace trigger test_tri
before insert on test
for each row
declare
v_val number;
--定义v_val,当使用序列插入时,将序列值放到将变量中。
v_num number;
--定义v_num,判断插入时使不使用序列。
begin
if :new.id = 0 then
--判断,当id使用的是默认值0时,代表使用序列
v_val:=test_seq.nextval;
loop
select count(id) into v_num from test where id = v_val;--查看test表的id列是否已存在跟序列相同的值,如果不存在,v_num = 0 。如果存在,v_num!=0;
if v_num != 0 then
v_val:=test_seq.nextval;--如果存在,则序列走一步。
end if;
if v_num = 0 then
exit;--如果不存在,则退出loop循环
end if;
end loop;
select v_val into :new.id from dual;--将序列值放进插入行,实现序列自增。
end if;
end;
/
--实现表自增功能触发器
如下图所示
以上第五次使用insert into test(name) values('测试');进行插入时,因为表里的id已存在1005了,所以触发器会循环一次,让序列走一下,变成1006;避免违反主键唯一约束。
猜你喜欢
- 2024-10-22 Oracle 创始人:全球 AI 监控将导致人们更好的行为
- 2024-10-22 oracle中merge into语句详解 oracle merger into
- 2024-10-22 oracle 数据库高效批量更新操作 MERGE INTO
- 2024-10-22 西门子PCS7之电机控制编程 西门子电机调试软件
- 2024-10-22 (Oracle 11g)使用expdp每周进行数据备份并上传到备份服务器
- 2024-10-22 Oracle Access Manager中的漏洞可以让攻击者模拟任何用户帐户
- 2024-10-22 SQL优化思路(以oracle为例) sql优化 oracle
- 2024-10-22 未找到Oracle客户端和?络组件”问题解决方法
- 2024-10-22 云贝教育 | Oracle 19c OCP数据库培训课,上课啦
- 2024-10-22 Oracle实现金额小写转大写函数 oracle 小写字母转大写
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- 前端设计模式 (75)
- 前端性能优化 (51)
- 前端模板 (66)
- 前端跨域 (52)
- 前端缓存 (63)
- 前端react (48)
- 前端aes加密 (58)
- 前端脚手架 (56)
- 前端md5加密 (49)
- 前端路由 (55)
- 前端数组 (65)
- 前端定时器 (47)
- Oracle RAC (73)
- oracle恢复 (76)
- oracle 删除表 (48)
- oracle 用户名 (74)
- oracle 工具 (55)
- oracle 内存 (50)
- oracle 导出表 (57)
- oracle 中文 (51)
- oracle链接 (47)
- oracle的函数 (57)
- mac oracle (47)
- 前端调试 (52)
- 前端登录页面 (48)
本文暂时没有评论,来添加一个吧(●'◡'●)