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

萝らか妹 提交于 2020-01-24 14:38:28

问题


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$;

回答1:


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.



来源:https://stackoverflow.com/questions/22903492/error-in-dynamic-statement-pl-pgsql-functions-and-operators-can-take-at-most-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!