Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in dynamic statement PL/PGSQL (functions and operators can take at most one set argument)

I am trying to execute the code below. I need this because, i wanted to pass the table names as parameters (character varying):

EXECUTE 'CREATE TABLE '||tmp_table||' AS SELECT study,
'||unnest(columns)||' AS variable_id, '||unnest_table(tblName)||
' AS variable_value FROM '||tblName;

However, I run into the error below:

functions and operators can take at most one set argument

Any ideas on how to solve this?

Here is the code for the unnest_table function:

CREATE OR REPLACE FUNCTION unnest_table(_tbl text)
RETURNS SETOF text LANGUAGE plpgsql AS $func$
BEGIN
    RETURN QUERY EXECUTE '
     SELECT unnest(ARRAY[' || (
SELECT string_agg(a.attname || '::text', ',' ORDER  BY a.attnum)
FROM   pg_catalog.pg_attribute a 
WHERE  a.attrelid = _tbl::regclass
AND    a.attnum > 0
AND    a.attisdropped = false
) || '])
FROM   ' || _tbl::regclass;

END
$func$;
like image 988
jackeblagare Avatar asked Oct 13 '25 06:10

jackeblagare


1 Answers

That's because unnest & your unnest_table both returns SETOF <sometype>, and operators can take at most one set argument, so f.ex.:

SELECT unnest(ARRAY['a', 'b', 'c']);

-- will return

unnest
------
"a"
"b"
"c"


SELECT unnest(ARRAY['a', 'b', 'c']) || 'd';

-- will return

?column?
--------
"ad"
"bd"
"cd"


SELECT unnest(ARRAY['a', 'b', 'c']) || 'd' || unnest(ARRAY['a', 'b', 'c']);

-- will return

ERROR: functions and operators can take at most one set argument
SQL state: 0A000

Edit: but i highly doubt, you want to create that much table with the same name - also EXECUTE does not accept more than one row:

ERROR: query "..." returned more than one row
SQL state: 21000

I think you should use something like the array_to_string() function.

like image 131
pozs Avatar answered Oct 15 '25 10:10

pozs