I have developed a function to UNION ALL tables from a list of table names (a table called tablelist below) inspired by this SO post.
The initial function just returns a selection, but now I'd like to write a new table with a name taken from a parameter new_table_name.
I'm struggling with the syntax to insert the parameter into the DROP TABLE AND CREATE TABLE statements. Here's one of the attempts which returns ERROR: mismatched parentheses at or near ";"
DROP FUNCTION IF EXISTS f_multi_union(text);
CREATE OR REPLACE FUNCTION f_multi_union(new_tab_name text)
RETURNS Table (my_id int, metric double precision, geom geometry)
LANGUAGE plpgsql AS
$func$
BEGIN
RETURN QUERY EXECUTE
(
DROP TABLE IF EXISTS working.'' || new_tab_name || '';
CREATE TABLE working.'' || new_tab_name || '' AS (
SELECT string_agg(format('SELECT * FROM %s', tbl), ' UNION ALL ')
FROM (SELECT tbl FROM working.tablelist) sub
)
);
END
$func$;
DROP TABLE IF EXISTS working.'' || new_tab_name || '';betweenBEGINandRETURN QUERY EXECUTE. Now givesERROR: syntax error at or near "''" LINE 8: DROP TABLE IF EXISTS working.'' || new_tab_name || '';Something wrong with syntax for calling parameter.formatpasses theDROPstatement but falls over @ERROR: syntax error at or near "CREATE" LINE 11: CREATE TABLE working.'' || new_tab_name || '' AS (My aim is to create a table that holds the contents of multipleUNION ALLs from a list of table namestablelist.