2

I'm trying to run a query that does a foreach of each element of an array, and then copies this to a directory with a custom named file. Here's the code I have presently:

DO
$do$
declare
    x varchar;
    y varchar;
    arr varchar[] := array['item1','item2'];
begin
    foreach x in array arr
    loop
        y := concat('C:\Outputs\output_' , x , '.csv');
        copy (select * from pdtable where pdtable.area = x) to y With CSV;
    end loop;
end
$do$

However this encounters an error in the copy statment at the to y statement. Is there an alternative way to do this?

1
  • EXECUTE format(...). Search for "postgres dynamic sql copy". Commented Sep 13, 2017 at 16:09

1 Answer 1

3

https://www.postgresql.org/docs/current/static/functions-string.html

DO
$do$
declare
    x varchar;
    y varchar;
    arr varchar[] := array['item1','item2'];
begin
    foreach x in array arr
    loop
        y := concat('C:\Outputs\output_' , x , '.csv');
        execute format('copy (select * from pdtable where pdtable.area = %L) to %L With CSV',x,y);
    end loop;
end
$do$
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.