How to return a table, from a POSTGRES Function?

Asked

Viewed 1,968 times

1

Hello, I’m trying to create a function in postgres, which at first is all correct, taking the return of function.

When I run the function, it is returning all lines, but all only in a field as a string. And I need it to come in table format.

How come: inserir a descrição da imagem aqui

How should I come: inserir a descrição da imagem aqui

MY JOB

CREATE OR REPLACE FUNCTION public.fc_comparar_comandos(var1 text,var2 text)
RETURNS TABLE ( p_cmap_id integer,
            p_cmap_cmd_id integer,
            p_cmd_nome text,
            p_cmap_parametro character varying,
            p_cmap_part_number character varying,
            p_cmap_ordem integer,
            p_cmap_level integer,
            p_teste text,
            p_cmd_param text,
            p_testado integer
) 
LANGUAGE 'plpgsql'
COST 1
VOLATILE 
ROWS 1000
AS $BODY$

DECLARE
    p_cmd     ALIAS FOR var1;
    p_pNumber ALIAS FOR var2;

BEGIN

RETURN QUERY

SELECT   cmap_id,
         cmap_cmd_id,
         cmd_nome,
         cmap_parametro,
         cmap_part_number,
         cmap_ordem,
         cmap_level,
         teste,
         (cmd.cmd_nome || ' ' ||cmd_aprovacao.cmap_parametro) as cmd_param,
         CASE WHEN teste IS NULL THEN 0 ELSE 1 END as testado
FROM cmd_aprovacao
INNER JOIN cmd ON cmd.cmd_id = cmd_aprovacao.cmap_cmd_id
LEFT JOIN (
            SELECT UNNEST(
                STRING_TO_ARRAY(p_cmd, ',')
               ) as teste
            ) t ON t.teste = (cmd.cmd_nome || ' ' ||cmd_aprovacao.cmap_parametro)
WHERE cmap_part_number = p_pNumber
AND cmap_level = (  SELECT MAX(cmap_level)
                    FROM cmd_aprovacao 
                    WHERE cmap_part_number = p_pNumber
                 )
ORDER BY cmap_ordem;

END

$BODY$;

1 answer

1


The problem is not in its function, it is in the way it is being called.

When you call your function that way:

SELECT public.fc_comparar_comandos( 'ABCD', 'XPTO' );

Postgres returns a single field of the type RECORD.

To get the "separate" columns, how about calling your function that way:

SELECT * FROM public.fc_comparar_comandos( 'ABCD', 'XPTO' );

Or:

SELECT
    p_cmap_id,
    p_cmap_cmd_id,
    p_cmd_nome,
    p_cmap_parametro,
    p_cmap_part_number,
    p_cmap_ordem,
    p_cmap_level,
    p_teste,
    p_cmd_param,
    p_testado
FROM
    public.fc_comparar_comandos('XPTO','ABCD');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.