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个数做限制.

相关推荐
薛定谔的算法13 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
Databend14 小时前
Databend 亮相 RustChinaConf 2025,分享基于 Rust 构建商业化数仓平台的探索
数据库
得物技术15 小时前
破解gh-ost变更导致MySQL表膨胀之谜|得物技术
数据库·后端·mysql
Raymond运维20 小时前
MariaDB源码编译安装(二)
运维·数据库·mariadb
沢田纲吉20 小时前
🗄️ MySQL 表操作全面指南
数据库·后端·mysql
RestCloud1 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud1 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence2 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger2 天前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥2 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql