CREATE OR REPLACE FUNCTION public.merge_test (
r_obj refcursor,
_ldeptid character varying
) RETURNS refcursor
LANGUAGE 'plpgsql' COST 100.0 VOLATILE AS $function$
BEGIN
DROP TABLE IF EXISTS tblCumulate;
create temp table tblCumulate (
lCompid varchar(10),
lOpenCount int default 0,
lClosedCount int default 0
);
DROP TABLE IF EXISTS tblOpen;
create temp table tblOpen (
lOSID SERIAL,
lCount numeric(24,0),
lCompid varchar(100)
);
MERGE into tblCumulate CUM using (select lcompid,lCount from tblopen) as OP
on CUM.lcompid=OP.lcompid
when matched
then update set cum.lOpenCount=op.lcount
when not matched
then insert (lCompid,lOpenCount) values op.lcompid,op.lcount);
open r_obj for
select * from tblCumulate;
return r_obj;
END;
$function$;
当我执行(运行)此过程时显示以下错误。
ERROR: "tblcumulate" is not a known variable
LINE 41: MERGE into tblCumulate CUM temp
MERGE
是在 PostgreSQL v15 中引入的。在此之前,您必须使用INSERT ... ON CONFLICT
。
无论如何,这里的问题是 PL/pgSQL 函数缓存已解析的语句。因此,在数据库会话中第一次执行该函数时,
tblCumulate
被解析为某个内部对象 ID,第二次执行将不再找到该对象。
您可以尝试的一件事是禁用执行计划的缓存;也许这足以解决问题:
ALTER FUNCTION public.merge_test (refcursor, character varying)
SET plan_cache_mode = force_custom_plan;
如果这还不够,你必须使用动态 SQL:
EXECUTE 'MERGE INTO tblCumulate ...';