POSTGRE SQL使用存储过程执行一段更新/插入语句,并返回一段查询的结果集

返回结果集使用的是:RETURNS TABLE + RETURN query

-- RETURNS "pg_catalog"."text" AS $BODY$ 原始日志
CREATE OR REPLACE FUNCTION "schema"."table1"("haha_name" varchar, "logo_url" varchar)
  RETURNS TABLE("col1" varchar, "col2" timestamp) AS $BODY$ 
	
DECLARE 	 haha_appid_var  varchar; 
DECLARE exc_sql text;
DECLARE exc_sql_appid text;

begin

 
exc_sql_appid = 'select  haha_appid   from schema.schema2
									where haha_name='''||haha_name||''' ;';
EXECUTE    exc_sql_appid into haha_appid_var ;

exc_sql =  'insert into schema.table1
select  haha_appid,t0.haha_logo ,CURRENT_TIMESTAMP as createdate,
			CURRENT_TIMESTAMP as freshtime,0 as status
from 
(select  '''||haha_name||'''::text as haha_name,'''||logo_url||''' as haha_logo  ) t0

left join 
(select haha_name,haha_appid from schema.table2
)t1
using(haha_name);';
EXECUTE    exc_sql;

--你可以任意选择你想要返回的表和字段,但是需要在  RETURNS TABLE 里添加对应的字段和类型。
RETURN query SELECT haha_logo as col1 ,createdate as col2 FROM schema.table1 
WHERE  haha_appid = haha_appid_var order by createdate desc
;
   
	 
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000```

你可能感兴趣的:(数据库)