Postgres Function End Loop and return Error

后端 未结 2 1216
长发绾君心
长发绾君心 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.

    0 讨论(0)
  • 2021-01-24 06:54

    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.

    0 讨论(0)
提交回复
热议问题