SAVEPOINT 是一个用于定义新保存点的事务命令。
SAVEPOINT 在 PostgreSQL 8.0 中被添加。
用法
保存点是使用 SAVEPOINT 命令在事务中创建的用户定义标记,可以回滚到该标记,而不会使整个事务失效。
保存点必须命名;名称可以任意,但必须遵循与其他数据库对象(如表和列标识符)相同的规则;有关更多详细信息,请参阅 PostgreSQL 文档的“标识符和关键字”部分。
变更历史
- PostgreSQL 8.0
- 添加(初始提交 cc813fc2)
示例
SAVEPOINT 的基本用法
postgres=# BEGIN;
BEGIN
postgres=*# SELECT 1;
?column?
----------
1
(1 row)
postgres=*# SAVEPOINT s1;
SAVEPOINT
postgres=*# SELECT foo;
ERROR: column "foo" does not exist
LINE 1: SELECT foo;
^
postgres=!# ROLLBACK TO SAVEPOINT s1;
ROLLBACK
postgres=*# SELECT 2;
?column?
----------
2
(1 row)
postgres=*# COMMIT;
COMMIT
请注意,保存点只能在事务块内使用
postgres=# SAVEPOINT s1; ERROR: SAVEPOINT can only be used in transaction blocks
事务错误后不能建立保存点
postgres=# BEGIN;
BEGIN
postgres=*# SELECT foo;
ERROR: column "foo" does not exist
LINE 1: SELECT foo;
^
postgres=!# SAVEPOINT foo;
ERROR: current transaction is aborted, commands ignored until end of transaction block
有效的保存点名称
postgres=*# SAVEPOINT foo; SAVEPOINT postgres=*# SAVEPOINT _foo; SAVEPOINT postgres=*# SAVEPOINT foo_bar_1; SAVEPOINT postgres=*# SAVEPOINT über1; SAVEPOINT
postgres=*# SAVEPOINT テスト; SAVEPOINT
postgres=*# SAVEPOINT "123"; SAVEPOINT postgres=*# SAVEPOINT "[foo]"; SAVEPOINT
无效的保存点名称
postgres=*# SAVEPOINT 1;
ERROR: syntax error at or near "1"
LINE 1: SAVEPOINT 1;
^
postgres=*# SAVEPOINT [foo];
ERROR: syntax error at or near "["
LINE 1: SAVEPOINT [foo];
^
参考资料
- PostgreSQL 文档: SAVEPOINT
