Would work like this:
CREATE OR REPLACE FUNCTION qwert(_tbl text, cols text[])
RETURNS numeric AS
$func$
BEGIN
EXECUTE format('
DROP TABLE IF EXISTS %1$I;
CREATE TEMPORARY TABLE %1$I AS
SELECT %2$s AS col_sum FROM src;'
,_tbl
,(SELECT string_agg(quote_ident(i), ' + ') FROM unnest(cols) i)
);
RETURN 1; -- still unclear? Add yourself ...
END
$func$ LANGUAGE PLPGSQL;
Call:
SELECT qwert('t1', ARRAY['x1','x2']);
Or:
SELECT qwert('t1', '{x1,x2}');
format()
requires Postgres 9.1 or later.
I use a text
parameters for the temp table name and an array of text
for the column names, then build the expression with a combination of unnest()
, quote_ident()
and string_agg()
. Don't forget to name the column (col_sum
in my ex.).
Details about sanitizing values for use as identifiers in this related answer on dba.SE. You can pass any number of columns this way.