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 o
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
orINOUT
parameters, theRETURNS
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:
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.