1

我尝试创建此函数,但系统返回“循环错误”,我不知道如何同时返回 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;
4

2 回答 2

2

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

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

于 2013-02-22T18:30:08.017 回答
2

使用OUT参数返回具有多列的单行。在这种情况下,类型是可选的,我在这里RETURN引用手册:

当有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);

我还大大简化了您的功能。其中:

  • 为您的作业使用“简单案例”
  • 使用连接将两个查询简化为一个。

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

于 2013-02-22T18:44:54.073 回答