从 postgres 函数返回带有错误代码和消息的 refcursor

returning a refcursor with error code and message from postgres function

我有一个 postgres 函数 return 是一个 refcursor :

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$;

现在我可以通过异常块得到任何错误,但我的要求是 return 错误代码和错误消息,以防我们遇到任何错误。这将通过 2 个额外的输出参数 o_errcode 和 o_errmsg.

来完成

当我尝试这个时,我得到了错误

ERROR:  function result type must be record because of OUT parameters
SQL state: 42P13

查询成功时如何获取游标,异常时如何获取错误信息和错误码

我需要实现这个,以便调用块在出现任何错误时得到一个错误代码 <> 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;