Postgres功能结束循环并返回错误

时间:2013-02-22 18:22:59

标签: function postgresql loops record plpgsql

我试图创建此函数但系统返回“LOOP错误”,我不知道如何同时返回3个变量。我已经尽力解决这个问题,但我没有在任何地方找到答案。

CREATE OR REPLACE FUNCTION conta_relatos(fator_normativo integer, fator_determinativo integer)
  RETURNS integer AS
$BODY$
DECLARE
    vinculos_encontrados RECORD;
    rel_pri INT;
rel_sec INT;
rel_ref INT;
no_item INT;
tipo_relato TEXT;
BEGIN
    rel_pri := 0;
    rel_sec := 0;
    rel_ref := 0;    
FOR vinculos_encontrados IN SELECT * FROM "Vinculos" WHERE ("Vinculos"."Fator_Normativo" =   Fator_Normativo AND "Vinculos"."Fator_Determinativo" = Fator_Determinativo) LOOP
    no_item := vinculos_encontrados."Item";
SELECT "Fontes"."Tipo_Relato" INTO tipo_relato FROM "Fontes" WHERE "Fontes"."ID" = no_item;
--IF tipo_relato = "1 - Relato Primário" THEN 
   rel_pri := rel_pri + 1;
--ELSE IF tipo_relato = "2 - Relato Secundário" THEN 
   rel_sec := rel_sec + 1;
--ELSE IF tipo_relato = "3 - Relato Referencial" THEN 
   rel_ref := rel_ref + 1;
    --END IF;
    END LOOP;
    RETURN rel_pri, rel_sec, rel_ref;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

2 个答案:

答案 0 :(得分:2)

要同时返回多个值,您需要指定OUT个参数,并将函数的返回类型更改为record。请参阅文档here。确保使用SELECT *调用该函数以将参数恢复为3列。

请更新您的问题以包含您收到的错误,如果我能提供帮助,我会更新此答案以解决此问题。

答案 1 :(得分:2)

使用OUT parameters返回包含多列的单行。在这种情况下,RETURN类型是可选的,我引用手册here

  

如果有OUTINOUT个参数,则可以省略RETURNS子句。

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;

呼叫:

SELECT * FROM conta_relatos(1,2);

我也大大简化了你的功能。其中包括:

  • 使用"Simple CASE"进行作业。
  • 使用连接将两个查询简化为一个。

整个函数可以很容易地重写为单个SQL语句。