当前位置:网站首页>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的数据没有插入,数据库排名数据却发生了变化。
边栏推荐
- Verify that the addShutdownHook hook takes effect
- Usage of EFR32 as sniffer for Zigbee/Thread
- VisualStudio2022 local debugging entry is particularly slow problem solving
- Code open source design and implementation ideas
- 模拟问题(上)
- ThinkPHP high imitation blue play cloud network disk system source code / docking easy payment system program
- [High Performance Computing] openMP
- 4. Web Development
- BindingExpression path error: 'selectMenusList' property not found on 'object' ''ViewModel'
- [MRCTF2020]Hello_misc
猜你喜欢
Excellent MySQL interview questions, 99% must ask in preparation for August!I can't pass the interview
GCC Rust is approved to be included in the mainline code base, or will meet you in GCC 13
Us to raise interest rates by 75 basis points in "technical recession"?Encryption market is recovering
Hexagon_V65_Programmers_Reference_Manual(11)
五、视图解析与模板引擎
mysql隔离级别
Record of problems encountered by the pyinstaller packager
GO语言学习笔记一
Machine Learning: Knowing the Dimensionality Reduction Process Through Low Variance Filtering
WPF introduces ttf icon file usage record
随机推荐
Hexagon_V65_Programmers_Reference_Manual(11)
三、依赖配置管理
String Problem (Part 1)
Catch That Cow (detailed)
Web page element parsing a tag
字符串问题(下)
22. Why do you need a message queue?What are the advantages of using the message queue?
双指针问题(下)
Excellent MySQL interview questions, 99% must ask in preparation for August!I can't pass the interview
nSoftware.PowerShell.Server.2020
Protobuf compound data types, speaking, reading and writing
How with Mexico Volkswagen VW EDI connection to Mexico
POJ1321 棋盘问题(详解)
uni-app realizes cross-end development of mobile phone Bluetooth to receive and send data
Go study notes (84) - Go project directory structure
IGBT wafers used in photovoltaic inverters
Some understanding of YOLOv7
【Vitis】ZCU102开发板PS端控制PL端复位的代码实现
Simulation problem (below)
05 Detailed explanation of the global configuration file application.properties