Calling a stored procedure within a stored procedure

天大地大妈咪最大 提交于 2019-11-29 11:33:31
mu is too short

COPY is a bit odd as it sort of treats its query argument as a string even though it isn't written as a string. The result is that the query:

SELECT * FROM retrieve_info($1, $2)

isn't executed in the context of the function, it is executed in the context of COPY itself. Even though you say:

copy (select * from t) ...

it is treated more as though you wrote:

copy 'select * from t' ...

so by the time the query is executed, the function parameters no longer have any meaning, the query argument to COPY may look like it would behave like a closure in other languages but it doesn't, it acts more like a string that gets passed to eval.

You can get around this strangeness by using the usual Kludge of Last Resort: dynamic SQL. You should get better results if you write your function to use string wrangling and EXECUTE:

create or replace function print_out(text, text) returns void as $$
begin
    execute 'copy ('
         || 'select * from retrieve_info'
         ||     '(' || quote_literal($1) || ',' || quote_literal($2) || ')'
         || ') to ''myfilepath/test.csv'' with csv header;';
end;
$$ language plpgsql;

Are x and y quoted intentionally?

COPY (SELECT * FROM retrieve_info('x','y')) TO 'myfilepath/test.csv'

You are not sending the x and y arguments of print_out to retrieve_info - rather, you are sending the strings 'x' and 'y'. Assuming you don't have records with method='x' AND species='y', it's of little wonder you get no results.

Try this instead:

COPY (SELECT * FROM retrieve_info(x,y)) TO 'myfilepath/test.csv'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!