pl/sql savepoint的使用

保存点(savepoint)是事务处理过程中的一个标志,和回滚命令(rollback)结合使用,主要的用途是允许用户将某一段处理回滚而不必回滚整个事务,这在pl/sql研发中还是非常有用处的。

下面的例子中,把savepoint标记在insert语句之前,如果这条insert语句试图将重复的数据保存到emp表中的话,将触发执行预先定义的dup_val_on_index例外处理,在这里面的rollback to do_insert命令将回滚上面的那条insert操作,而不会影响前面的所有操作。

declare

emp_id emp.empno%type;

begin

update emp set ... where empno = emp_id;

delete from emp where ...

...

savepoint do_insert;

insert into emp values (emp_id, ...);

exception

when dup_val_on_index then

rollback to do_insert;

end;

如果你定义了多个savepoint,当你指定回滚到某个savepoint时,那么回滚操作将回滚这个savepoint后面的所有操作(即使后面可能标记了n个savepoint)。例如,在一段处理中

你定义了五个savepoint,从第三个savepoint回滚,后面的第四、第五个标记的操作都将被回滚,如果不使用rollback to savepoint_name而使用rollback,将会滚整个事务处理。

如果你在递归子程式里面定义了一个savepoint, 如果每一个递归层都设置了savepoint. 此时, 你只能回滚到最近的一个savepoint.

savepoint的声明能在同一个事务处理里面重复定义. 他的作用就是把savepoint从上一个位置转移到目前的位置. 因而,执行回滚也只回滚到最近的savepoint.

下面是个例子:

begin

...

savepoint my_point;

update emp set ... where empno = emp_id;

...

savepoint my_point; -- move my_point to current point

insert into emp values (emp_id, ...);

exception

when others then

rollback to my_point;

end;

另外,oracle没有对每个session里面能使用的savepoint个数做限制.

相关推荐
wuyunhang1234568 分钟前
MySQL----触发器
数据库·mysql
ptc学习者22 分钟前
OGG 安装注意事项
java·开发语言·数据库
鸽鸽程序猿1 小时前
【MySQL】索引
数据库·mysql
zym大哥大1 小时前
Redis-Zest
数据库·redis·缓存
zl9798992 小时前
Redis-stream、bitfield类型
数据库·redis·缓存
数据库那些事儿2 小时前
Qoder + ADB Supabase :5分钟GET超火AI手办生图APP
数据库·后端
IvorySQL2 小时前
PostgreSQL 18 异步 I/O(AIO)调优指南
数据库·postgresql
kakacc:2 小时前
记录一次巧妙的SQL:一对多关联导致的 sum () 、count()等group函数重复计算问题
数据库·sql
心随雨下2 小时前
Redis中Geospatial 实际应用指南
数据库·redis·分布式·缓存
黑夜管理员2 小时前
Sql Server安装报错“服务没有及时响应启动或控制请求”
数据库·sql server