当前位置:网站首页>oracle触发器的自治事务
oracle触发器的自治事务
2022-07-30 05:08:00 【心寒丶】
1、插入数据,名次依次+1
今天有朋友提问说 ,oracle数据库怎么实现这个功能:
有一个排名表,插入一条数据排名为1的数据,之前表里数据1变成2,2,变成3类推、插入2,之前表里2变3,3变4类推,首先想到了触发器,在插入数据之前把排名大于等于当前的名次依次+1来实现。
比如表数据如下,rank字段代表名次

编写触发器如下:
create or replace trigger TRI_add
before insert on b
for each row
declare
begin
update b set b.RANk=b.RANk+1 where b.RANk>:new.RANk or b.RANk=:new.RANk ;
end TRI_add;
触发器创建好之后,插入一条数据测试一下:
insert into b (ID, RANk) values (3, 1);
插入数据后结果如下:

可以看到插入第一名之后,原来id为1的第一名rank标称了2,原来id为2的第二名rank变成了3,基本需求也算是满足了。
2、触发器自治事务,数据回滚,则触发器不回滚实现
朋友又问我说,你这个插入数据的时候回滚掉,那么原来排名的名次不会换掉,我现在如果插入数据再回滚,然后之前的排名任然+1这个怎么实现呢。
这个时候我们就可以使用自治事务,在触发器触发期间提交掉事务,不管插入数据的事务是否成功,因此在以上触发器上修改如下:
create or replace trigger TRI_add
before insert on b
for each row
declare
PRAGMA autonomous_transaction;
begin
update b set b.RANk=b.RANk+1 where b.RANk>:new.RANk or b.RANk=:new.RANk ;
commit;
end TRI_add;
实际上就是增加了这两行
这个时候恢复数据,然后再执行插入数据,之后回滚再看结果
insert into b (ID, RANk) values (3, 1);

可以观察到id为3的数据没有插入,数据库排名数据却发生了变化。
边栏推荐
- A must see for software testers!Database knowledge MySQL query statement Daquan
- 小程序npm包--API Promise化
- Let's talk about what SaaS is, and the problems encountered...
- C# One Week Introductory "C# - Classes and Objects" Day Six
- mysql无法远程连接 Can‘t connect to MySQL server on ‘xxx.xxx.xxx.xxx‘ (10060 “Unknown error“)
- 复现XXL-JOB 任务调度中心后台任意命令执行漏洞
- ThinkPHP高仿蓝奏云网盘系统源码/对接易支付系统程序
- Machine Learning: Knowing the Dimensionality Reduction Process Through Low Variance Filtering
- [Verilog] HDLBits Problem Solution - Circuits/Combinational Logic
- Predictive maintenance scheduling of multiple power equipment based on data-driven fault prediction
猜你喜欢

美国再次加息75个基点 陷入“技术性衰退”?加密市场却呈现复苏力量

Whole process scheduling - Azkaban entry and advanced

小程序使用npm包定制全局样式

Unity3D Application simulation enters the front and background and pauses

WPF study notes "WPF Layout Basics"

QT(39)-vs development qt program prompts that the source file cannot be opened

nSoftware.PowerShell.Server.2020

Using the GPU parallel computing 】 【 OpenCL&OpenCLUtilty GPU parallel computing

L2-025 分而治之

Discourse Custom Header Links
随机推荐
模拟问题(上)
go语言学习笔记二
go language study notes 4
webService接口
Hexagon_V65_Programmers_Reference_Manual (11)
Acwing完全数
handler+message [message mechanism]
Unity踩坑记录 —— GetComponent的使用
罗湖区工匠技能领军人才奖励项目申请指南
聊一聊什么是SaaS,以及遇到的问题......
字符串问题(下)
坪山区关于开展2022年度科技创新专项资金申报工作的通知
nSoftware.PowerShell.Server.2020
Verify that the addShutdownHook hook takes effect
Golang eight-legged text finishing (continuous handling)
(RCE) Remote Code/Command Execution Vulnerability Vulnerability Exercise
Three Solutions for SaaS Multi-tenant Data Isolation
Seven, custom configuration
std::vector中保存指针时用法
Unity stepping on the pit record - the use of GetComponent