问题
I have tried to create this function but the system is returning a "LOOP error" and I don't know how to return 3 variables at the same time. I've tried hard to figure this out but I didn't find an answer anywhere.
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;
回答1:
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
OUTorINOUTparameters, theRETURNSclause 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.
回答2:
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.
来源:https://stackoverflow.com/questions/15030722/postgres-function-end-loop-and-return-error