postgreSQL(一) 函数事务

798 阅读1分钟
  1. 第一种情况:
    第一个代码块和第二个代码块都没有提交。
    如果整个函数捕获到了异常,即执行到了“总异常”处,则整个函数都不会提交。即使第一个begin end块虽然没有异常,正确执行,但还是不会提交事务。
  2. 第二种情况:
    第一个代码块提交,第二个代码块没提交。
  3. 总结:
    异常在哪个块捕获到,就影响哪个块的begin..end中的事务提交。
-- 测试事务
create or replace function test_tsct()
returns integer 
as $BODY$
declare
	result integer;
begin
	
	begin
	INSERT INTO public.user_info(
	id,name, birthday, address, created_date)
	VALUES (uuid_generate_v4(), 'name_3',to_date('1986-7-7','yyyy-mm-dd') , '成都', now());
	exception
			when others then
			insert into t_log (msg) values('1异常');
	end;		
			
	-- 第一种情况,全部回滚	
	-- result=1/0;
			
	begin
	INSERT INTO public.user_info(
	id,name, birthday, address, created_date)
	VALUES (uuid_generate_v4(), 'name_4',to_date('1986-7-7','yyyy-mm-dd') , '成都', now());
        -- 第二种情况,只是本begin end代码块不提交		
	result=1/0;		
	exception
			when others then
			insert into t_log (msg) values('2异常');
	end;		

	return 1;
	
exception
			when others then
			insert into t_log (msg) values('总异常');
			return 0;
			
end;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;