当前位置:网站首页>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的数据没有插入,数据库排名数据却发生了变化。
边栏推荐
- go语言学习笔记四
- C. Qualification Rounds
- webService interface
- 05 Detailed explanation of the global configuration file application.properties
- Acwing perfect number
- 1315_使用LOOPBACK模拟模式pyserial安装是否成功的测试
- Excellent MySQL interview questions, 99% must ask in preparation for August!I can't pass the interview
- QT(39)-vs development qt program prompts that the source file cannot be opened
- js operation to add or subtract from the current date (day, week, month, year)
- gnss rtcm rtklib Ntrip...
猜你喜欢
五、视图解析与模板引擎
[3D Detection Series-PointRCNN] Reproduces the PointRCNN code, and realizes the visualization of PointRCNN3D target detection, including the download link of pre-training weights (starting from 0 and
七、自定义配置
动态规划问题(完结篇)
Small programs use npm packages to customize global styles
Whole process scheduling - Azkaban entry and advanced
The Complete Go Books - Beginner to Advanced and Web Development
Predictive maintenance scheduling of multiple power equipment based on data-driven fault prediction
Unity3D Application simulation enters the front and background and pauses
nSoftware.PowerShell.Server.2020
随机推荐
go language study notes 4
The Azure developer news 丨 memorabilia in July
Learning of redis_Basic part
C语言实现安全性极高的游戏存档并读档
解决go环境编译不了exe
四、Web开发
Code open source design and implementation ideas
LeetCode Algorithm 328. Parity linked list
Detailed explanation of REUSE_ALV_GRID_DISPLAY
mysql隔离级别
Get the local IP and Request's IP
How with Mexico Volkswagen VW EDI connection to Mexico
Code readability, pre-checks, comments and summaries
The Complete Go Books - Beginner to Advanced and Web Development
小程序使用npm包定制全局样式
Solve the go environment can not compile exe
L2-025 分而治之
handler+message [message mechanism]
Acwing perfect number
Stimulsoft ReportsJS and DashboardsJS. 2022.3.3