I am brand new in PL/pgSQL. We have a Postgres 11 database.
I need a function that takes 1 argument as an ID of one table and do a recursive search in another. It should return two columns: id
and concatenated result as a text
(or varchar
).
Here is my code (more like pseudocode):
DROP FUNCTION IF EXISTS;
CREATE OR REPLACE FUNCTION my_awesome_func(AUID, UUID) RETURNS (RESULT TEXT) AS;
DECLARE RESULT TEXT;
BEGIN;
SELECT first_table.parent_uid FROM first_table WHERE first_table.auid = AUID;
WITH RECURSIVE child_to_parents AS (
SELECT second_table.* FROM second_table
WHERE aoguid = first_table.parent_uid
UNION ALL
SELECT second_table.* FROM second_table.*, child_to_parents
WHERE second_table.aoguid = child_to_parents.parentguid
AND second_table.currstatus = 0
)
END
SELECT * FROM child_to_parents ORDER BY aolevel;
The fiddle is here:
https://dbfiddle.uk/?rdbms=postgres_11&fiddle=dfa2838ab11356cc08987d0931f7b8e5