[英]returning a refcursor with error code and message from postgres function
我有一个返回 refcursor 的 postgres function:
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$;
现在我可以通过异常块得到任何错误,但我的要求是返回错误代码和错误消息,以防我们遇到任何错误。 这将通过 2 个额外的输出参数 o_errcode 和 o_errmsg 来完成。
当我尝试这个时,我得到了错误
ERROR: function result type must be record because of OUT parameters
SQL state: 42P13
在成功查询的情况下如何获取 cursor 以及在任何异常情况下的错误消息和错误代码。
我需要实现这一点,以便调用块在出现任何错误时获得错误代码<> 0,并且我立即停止进程并记录错误(我正在通过 ins_error_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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.