在 PostgreSQL 的事務中;執行的SQL遇到錯誤(書寫,約束限制);該事務的已經執行的SQL都會進行rollback。那如何忽略其中的錯誤。將SQL執行到底?在事務中設置 ON_ERROR_ROLLBACK 即可。
下面演示
1、未作任何設置
演示腳本
begin;
-- 1、創建表tbl_test_01
create table tbl_test_01(id int primary key, info text);
-- 2、插入異常數據
insert into tbl_test_01 values ('hello', 'PostgreSQL');
-- 3、插入正常數據
insert into tbl_test_01 values (1001, 'PostgreSQL');
end;
執行過程
postgres=# begin;
BEGIN
postgres=# create table tbl_test_01(id int primary key, info text);
CREATE TABLE
postgres=# insert into tbl_test_01 values ('hello', 'PostgreSQL');
ERROR: invalid input syntax for type integer: "hello"
LINE 1: insert into tbl_test_01 values ('hello', 'PostgreSQL');
^
postgres=# insert into tbl_test_01 values (1001, 'PostgreSQL');
ERROR: current transaction is aborted, commands ignored until end of transaction block
postgres=# end;
ROLLBACK
postgres=# \d tbl_test_01
Did not find any relation named "tbl_test_01".
執行結果
- 執行結果是ROLLBACK
- 執行的正常SQL也ROLLBACK
2、設置 ON_ERROR_ROLLBACK
演示腳本
begin;
\set ON_ERROR_ROLLBACK interactive
create table tbl_test_01(id int primary key, info text);
insert into tbl_test_01 values ('hello', 'PostgreSQL');
insert into tbl_test_01 values (1001, 'PostgreSQL');
end;
執行過程
postgres=# begin;
BEGIN
postgres=# \set ON_ERROR_ROLLBACK interactive
postgres=# create table tbl_test_01(id int primary key, info text);
CREATE TABLE
postgres=# insert into tbl_test_01 values ('hello', 'PostgreSQL');
ERROR: invalid input syntax for type integer: "hello"
LINE 1: insert into tbl_test_01 values ('hello', 'PostgreSQL');
^
postgres=# insert into tbl_test_01 values (1001, 'PostgreSQL');
INSERT 0 1
postgres=# end;
COMMIT
postgres=# \d tbl_test_01
Table "public.tbl_test_01"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
id | integer | | not null |
info | text | | |
Indexes:
"tbl_test_01_pkey" PRIMARY KEY, btree (id)
postgres=# select * from tbl_test_01;
id | info
------+------------
1001 | PostgreSQL
(1 row)
執行結果
- 執行結果是COMMIT
- 表 tbl_test_01 成功創建
- 數據 (1001, 'PostgreSQL') 也成功插入