Postgresql 从postgres函数返回带有错误代码和消息的refcursor
我有一个返回refcursor的postgres函数:Postgresql 从postgres函数返回带有错误代码和消息的refcursor,postgresql,plpgsql,pgadmin,Postgresql,Plpgsql,Pgadmin,我有一个返回refcursor的postgres函数: CREATE OR REPLACE FUNCTION ngfcst.meta_user_preference_error_test_go(--need to add -- inout o_errcode varchar, inout o_errmsg varchar-- i_login character varying, i_pref_type character varying DEFAULT NULL::charact
CREATE OR REPLACE FUNCTION ngfcst.meta_user_preference_error_test_go(--need to add -- inout o_errcode varchar, inout o_errmsg varchar--
i_login character varying,
i_pref_type character varying DEFAULT NULL::character varying)
RETURNS refcursor
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
AS $BODY$
DECLARE
ref refcursor='o_user_pref_cur'; -- Declare a cursor variable
declare
err_context text;
BEGIN
if i_pref_type is NULL THEN
OPEN ref FOR
select * from ngfcst.ORG_USER_PREFERENCE where login=i_login;
else
OPEN ref FOR
select * from ngfcst.ORG_USER_PREFERENCE oup where oup.login=i_login and oup.pref_type=i_pref_type;
end if;
RETURN ref; -- Return the cursor to the caller
exception
when others then
GET STACKED DIAGNOSTICS err_context = PG_EXCEPTION_CONTEXT;
RAISE WARNING 'Error Name:%',SQLERRM;
RAISE WARNING 'Error State:%', SQLSTATE;
RAISE WARNING 'Error Context:%', err_context;
CALL ngfcst.ins_error_logs( SQLSTATE, err_context, '','','ngfcst.meta_user_preference_error_test');
return -1;
END;
$BODY$;
现在我可以通过异常块获得任何错误,但我的要求是在遇到任何错误时返回错误代码和错误消息。这将由两个额外的输出参数o_errcode和o_errmsg完成
当我尝试这个时,我得到了错误
ERROR: function result type must be record because of OUT parameters
SQL state: 42P13
如果查询成功,如何获取光标;如果出现异常,如何获取错误消息和错误代码
我需要实现这一点,以便调用块在出现任何错误时获得错误代码0,我立即停止进程并记录错误(我通过ins\U error\U logs过程执行此操作)使用三个
OUT
参数。例如:
CREATE FUNCTION meta_user_preference_error_test_go(
IN i_login text,
OUT o_errcode text,
OUT o_errmsg text,
OUT o_cursor refcursor,
IN i_pref_type text DEFAULT NULL
) RETURNS record LANGUAGE plpgsql
AS $$BEGIN
o_errcode := '0';
o_errmsg := 'SUCCESS';
o_cursor := 'o_cursor';
OPEN o_cursor FOR SELECT 42;
END;$$;
BEGIN;
SELECT * FROM meta_user_preference_error_test_go('login');
o_errcode | o_errmsg | o_cursor
-----------+----------+----------
0 | SUCCESS | o_cursor
(1 row)
FETCH ALL FROM o_cursor;
?column?
----------
42
(1 row)
COMMIT;
一如往常,这是可行的。非常感谢Laurenz:)嗨Laurenz,我看到你对Postgresql非常流利。我曾尝试过许多文献资料和培训,但我无法获得深入的知识。你能推荐一些可以指导高级Postgresql和pl/pgsqlAny建议Laurenz的学习材料吗?阅读Postgresql文档。这是我唯一读过的东西。它包含了一切,非常清晰。