I'd like a function that returns a text string of comma-separated column headers for a given table name. the code below compiles fine and does not produce any errors, however I can't get it to return anything other than NULL for tables that do and do not exist.
CREATE OR REPLACE FUNCTION myschema.return_column_list(tab_name TEXT)
RETURNS text AS
$BODY$
DECLARE
one_column record;
column_list TEXT;
BEGIN
FOR one_column IN
SELECT column_name FROM information_schema.columns
WHERE table_schema = 'myschema'
AND table_name = format('%s', tab_name)
LOOP
column_list = column_list || one_column || ',';
END LOOP;
column_list = left(column_list,length(column_list) - 1);
RETURN column_list;
END;
$BODY$ LANGUAGE 'plpgsql';
Update:
finally got it working by changing the DECLARE section from
DECLARE
one_column record;
column_list TEXT;
to
DECLARE
one_column record;
column_list TEXT = '';
as per the first example here. Spent the whole morning trying to figure this one out, can anyone explain why I have to do this?
one_columnis a record that contains a single attribute. To get the actualcolumn_namevalue you have to useone_column.column_name.column_list TEXT;initializedcolumn_listtonull. Concatenating values to anullvalue yieldsnull