1.测试表准备
-- 1.准备插入数据得表
create table t_tx(
id serial primary key,
name varchar(255) not null,
age int not null
)
-- 2.记录异常得表
create table t_log(
id serial primary key,
msg varchar(255)
)
2.第一种情况测试-子事务1出现异常
函数(存储过程)代码如下:
-- 测试子事务1出现异常
create or replace function test_tx() returns void as
$$
declare
result integer;
-- 1.全局事务
begin
-- 1.子事务1
begin
INSERT INTO t_tx(name,age) VALUES ('事务1',18);
result=1/0;
exception
when others then
insert into t_log (msg) values('子事务1发生异常');
end;
-- 2.子事务2
begin
INSERT INTO t_tx(name,age) VALUES ('事务2',18);
exception
when others then
insert into t_log (msg) values('子事务1发生异常');
end;
INSERT INTO t_tx(name,age) VALUES ('全局事务',18);
exception
when others then
insert into t_log (msg) values('全局事务发生异常');
end;
$$ LANGUAGE 'plpgsql' VOLATILE;
执行代码为:
select test_tx();
s