Postgres Function End Loop and return Error

后端 未结 2 1215
长发绾君心
长发绾君心 2021-01-24 05:57

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

2条回答
  •  深忆病人
    2021-01-24 06:42

    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 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;
    

    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.

提交回复
热议问题