gpt4 book ai didi

function - Postgres 函数结束循环并返回错误

转载 作者:行者123 更新时间:2023-11-29 12:38:21 24 4
gpt4 key购买 nike

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

最佳答案

使用OUT parameters返回包含多列的单行。 RETURN 类型在这种情况下是可选的,我引用手册 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;

调用:

SELECT * FROM conta_relatos(1,2);

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

  • 使用"Simple CASE"为你的任务。
  • 通过联接将两个查询简化为一个查询。

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

关于function - Postgres 函数结束循环并返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15030722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com