HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to refer to individual columns of a record returned by a function?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
referreturnedindividualcolumnsfunctionrecordhow

Problem

I have a function that returns setof record type.

CREATE TYPE CIR_TYPE AS
(
    ID integer,
    path text,
    cycle boolean
);

CREATE OR REPLACE FUNCTION circular_ref() RETURNS setof CIR_TYPE AS $body$

DECLARE
    r CIR_TYPE;

BEGIN
    For r in WITH RECURSIVE graph(ID, path, cycle) AS (
                SELECT id AS id
                     , ARRAY[parentid, id] AS path
                     , (parentid = id) AS cycle    
                FROM  mytable

                UNION ALL

                SELECT d.id, d.parentid ||path, d.parentid = ANY(path)
                FROM   graph g
                JOIN   mytable d ON d.id = g.path[1]
                WHERE  NOT g.cycle
             )
             SELECT DISTINCT *
             FROM   graph
    Loop

        If r.cycle= TRUE then
        Return NEXT r;
        End if;

    End loop;

END;
$body$ LANGUAGE plpgsql;


When I execute the above function I get an output like below:

circular_ref
----------------------------
(0,"{1,0,1}",t)
(1,"{0,1,0}",t)


Here 0 and 1 are ID, {0,1,0} and {0,1,0} are path and t indicates cycle.

I want to print the output like

ID     |    Path
----       ------
0      |   1,0,1
1      |   0,1,0


Please suggest how to get the expected result.

Solution

The problem, I guess, hits everyone starting with PostgreSQL. Fortunately, the solution is rather easy: simply call

SELECT * FROM circular_ref();


instead of

SELECT circular_ref();


This way it won't be a single record you get but a proper row. This way, you can even do

SELECT id, path FROM circular_ref();


to get the columns you want.

Code Snippets

SELECT * FROM circular_ref();
SELECT circular_ref();
SELECT id, path FROM circular_ref();

Context

StackExchange Database Administrators Q#65127, answer score: 8

Revisions (0)

No revisions yet.