当前位置:网站首页>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的数据没有插入,数据库排名数据却发生了变化。
边栏推荐
- Three Solutions for SaaS Multi-tenant Data Isolation
- js operation to add or subtract from the current date (day, week, month, year)
- How with Mexico Volkswagen VW EDI connection to Mexico
- go语言学习笔记三
- Weight line segment tree + line segment tree split/merge + CF1659D
- mysql无法远程连接 Can‘t connect to MySQL server on ‘xxx.xxx.xxx.xxx‘ (10060 “Unknown error“)
- Catch That Cow (detailed)
- BindingExpression path error: 'selectMenusList' property not found on 'object' ''ViewModel'
- String Problem (Part 1)
- 小程序使用npm包定制全局样式
猜你喜欢

Machine Learning: Knowing the Dimensionality Reduction Process Through Low Variance Filtering

Naive Bayes Classification

How with Mexico Volkswagen VW EDI connection to Mexico

工作效率-十五分钟让你快速学习Markdown语法到精通排版实践备忘
Go study notes (84) - Go project directory structure

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

Seven, custom configuration

IGBT wafers used in photovoltaic inverters

Golang channel implementation principle

Unity3D Application simulation enters the front and background and pauses
随机推荐
Usage when saving pointers in std::vector
Web page element parsing a tag
如何与墨西哥大众VW Mexico建立EDI连接
Small program npm package--API Promise
(RCE) Remote Code/Command Execution Vulnerability Vulnerability Exercise
go language study notes 3
小程序npm包--API Promise化
Protobuf compound data types, speaking, reading and writing
Discourse Custom Header Links
1315_Use the LOOPBACK simulation mode to test whether the pyserial installation is successful
四、Web开发
SVN View Username and Password
Simulation problem (below)
Usage of EFR32 as sniffer for Zigbee/Thread
三、依赖配置管理
模拟问题(上)
Catch That Cow(详解)
Get the local IP and Request's IP
[High Performance Computing] openMP
L2-020 功夫传人