I am running Postgres 9.3 on MacOSX. I am trying to add a COPY statement inside a function for an automatized save-to-file process.
I am new to any kind of sql codin
A quickly hacked together example using PLPGSQL
instead of SQL
.
Caveat: must be created as a superuser.
Replace the query etc in the function to whatever you need, and you can add in more input parameters to the function to create your query or output file(s) differently depending on what those input parameters are.
CREATE OR REPLACE FUNCTION copy_out_example ( p_path TEXT, p_filename_prefix TEXT, OUT file_and_path TEXT )
RETURNS TEXT AS
$func$
DECLARE
qry TEXT;
BEGIN
file_and_path := RTRIM(p_path,'/') || '/' || p_filename_prefix || '_' || ceil(random() * 1000000)::TEXT || '.csv';
qry := FORMAT('COPY (select * from pg_catalog.pg_class) TO %L CSV HEADER',file_and_path);
EXECUTE qry;
END;
$func$ LANGUAGE plpgsql STRICT SECURITY DEFINER;
SELECT copy_out_example('/path/to/the/file','some_test_file');
Results in a file like '/path/to/the/file/some_test_file_994216.csv'