Postgres Function End Loop and return Error

℡╲_俬逩灬. 提交于 2019-12-02 03:11:48

Use OUT parameters to return a single row with multiple columns. The RETURN type is optional in this case, I quote the manual here:

When there are OUT or INOUT parameters, the RETURNS clause can be omitted.

CREATE OR REPLACE FUNCTION conta_relatos(
    _fator_normativo integer
   ,_fator_determinativo integer
   ,OUT rel_pri integer
   ,OUT rel_sec integer
   ,OUT rel_ref integer
   ) AS
$func$
DECLARE
   tipo_relato text;
BEGIN

rel_pri := 0;
rel_sec := 0;
rel_ref := 0;

FOR tipo_relato IN
   SELECT f."Tipo_Relato"
   FROM   "Vinculos" v
   JOIN   "Fontes"   f ON f."ID" = v."Item"
   WHERE  v."Fator_Normativo" = _fator_normativo
   AND    v."Fator_Determinativo" = _fator_determinativo
LOOP
   CASE tipo_relato
   WHEN '1 - Relato Primário' THEN 
      rel_pri := rel_pri + 1;
   WHEN '2 - Relato Secundário' THEN 
      rel_sec := rel_sec + 1;
   WHEN '3 - Relato Referencial' THEN 
      rel_ref := rel_ref + 1;
   END CASE;
END LOOP;

-- No RETURN needed, OUT parameters are returned automatically.

END
$func$ LANGUAGE plpgsql;

Call:

SELECT * FROM conta_relatos(1,2);

I also largely simplified your function. Among others:

  • Use "Simple CASE" for your assignments.
  • Simplify two queries into one with a join.

The whole function could easily be rewritten as a single SQL statement.

To return multiple values at the same time, you'll want to specify OUT parameters and change the return type of the function to record. See the documentation here. Make sure to call the function with SELECT * to get the parameters back as 3 columns.

Please update your question to include the error you are getting, and if I can help I will update this answer to address it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!