简体   繁体   English

Postgres PL / pgSQL函数结果到文件,文件名作为参数

[英]Postgres PL/pgSQL Function results to file, with filename as argument

I am migrating some client side stuff into the server, and want to put it into a function. 我正在将一些客户端内容迁移到服务器中,并希望将其放入函数中。

I need to get the results of a query into a CSV file. 我需要将查询结果转换为CSV文件。 But, I'd like to pass the file name/location of the resulting file as an argument of the function. 但是,我想将结果文件的文件名/位置作为函数的参数传递。

So, this is a simple example of what I want to do: 因此,这是我想做的一个简单示例:

CREATE FUNCTION send_email_results(filename1 varchar) RETURNS void AS $$
DECLARE
BEGIN
    COPY(SELECT * FROM mytable) TO filename1 WITH CSV;
END;
$$ LANGUAGE plpgsql;

Postgres is complaining about this though, as it is translating the filename1 argument to '$1', and it doesn't know what to do. 但是Postgres对此有所抱怨,因为它将filename1参数转换为'$ 1',并且它不知道该怎么做。

I can hardcode the path if need be, but being able to pass it as a parameter sure would be handy. 我可以根据需要对路径进行硬编码,但是能够将其作为参数传递肯定会很方便。

Anyone have any clues? 有人有任何线索吗?

I just ran in to this. 我只是碰到这个。 It turns out that you can't use parameterized arguments when the copy command is used (at least that's the case with python as the stored proc language). 事实证明,使用复制命令时不能使用参数化的参数(至少python作为存储的proc语言就是这种情况)。 So, you have to build the command without arguments, like: 因此,您必须构建不带参数的命令,例如:

CREATE FUNCTION send_email_results(filename1 varchar) RETURNS void AS $$
DECLARE
BEGIN
    execute 'copy (select * frommytable) to ' || filename1 || ' with csv;';
END;
$$ LANGUAGE plpgsql;

You might have to use the quoting feature to make it a little more readable. 您可能必须使用报价功能才能使其更具可读性。 I don't know, I don't use plpgsql as a postgres function language, so the syntax might be wrong. 我不知道,我不使用plpgsql作为postgres函数语言,因此语法可能是错误的。

execute 'copy (select * frommytable) to ' || quote_literal(filename1) || ' with csv;'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM