Question

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. 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.

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?

Was it helpful?

Solution

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). 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.

execute 'copy (select * frommytable) to ' || quote_literal(filename1) || ' with csv;'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top