当前位置:网站首页>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的数据没有插入,数据库排名数据却发生了变化。
边栏推荐
- Classification of decision tree classification
- 复现XXL-JOB 任务调度中心后台任意命令执行漏洞
- The Double Pointer Problem (Part 2)
- mysql隔离级别
- Excellent MySQL interview questions, 99% must ask in preparation for August!I can't pass the interview
- ms project2010项目管理软件使用技巧总结
- Using the GPU parallel computing 】 【 OpenCL&OpenCLUtilty GPU parallel computing
- Unity stepping on the pit record - the use of GetComponent
- Us to raise interest rates by 75 basis points in "technical recession"?Encryption market is recovering
- 双指针问题(下)
猜你喜欢

Discourse Custom Header Links

Learning of redis_Basic part

ThinkPHP high imitation blue play cloud network disk system source code / docking easy payment system program

Golang eight-legged text finishing (continuous handling)

Solve the error SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xb7 in position 0: invalid start b

std::vector中保存指针时用法

mysql isolation level

五、视图解析与模板引擎

VisualStudio2022 local debugging entry is particularly slow problem solving

The Complete Go Books - Beginner to Advanced and Web Development
随机推荐
js operation to add or subtract from the current date (day, week, month, year)
需求设计文档和产品经理的角色改变
handler+message [message mechanism]
Verify that the addShutdownHook hook takes effect
Hexagon_V65_Programmers_Reference_Manual (10)
Xiamen SenseCore Technology MC3172(1): Introduction and Environment Construction
Learning of redis_Basic part
2.6 Radix sort (bucket sort)
How with Mexico Volkswagen VW EDI connection to Mexico
LeetCode Algorithm 2326. Spiral Matrix IV
protobuf 中复合数据类型的读写
WPF recursively obtains the list of specified control types in the form
Unity踩坑记录 —— GetComponent的使用
Hexagon_V65_Programmers_Reference_Manual (11)
Whole process scheduling - Azkaban entry and advanced
[MRCTF2020]Hello_misc
webService interface
【Vitis】ZCU102开发板PS端控制PL端复位的代码实现
Get the local IP and Request's IP
Dynamic Programming Problems (End)