0

I try to create a dynamic function that exports data specific ids controlled by a for, but when I run the function it shows me the error that there is no column i , I would like to concatenate the variable i with the name of the output file

CREATE OR REPLACE FUNCTION mifuncion() RETURNS void AS $$
BEGIN
  FOR i IN 1..5 LOOP
    copy (select nombre,dni,edad from test where id=i) TO 'C:\Users\Usuario\Documents\user'+i+'.csv' WITH  CSV HEADER;
  END LOOP;
END;
$$ LANGUAGE plpgsql;

2 Answers 2

2

COPY doesn't support query parameters, so you can't use PL/PGSQL variables with COPY.
You should use dynamic SQL with EXECUTE instead. You could declare variables to store query statement and file path, and then execute it like this

EXECUTE FORMAT('COPY (%s) TO %L WITH CSV HEADER', your_query, file_path);

OR

EXECUTE FORMAT('COPY (%s) TO %L WITH CSV HEADER', 'SELECT nombre, dni, edad FROM test WHERE id = ' || i, 'C:\Users\Usuario\Documents\user' || i || '.csv');
Sign up to request clarification or add additional context in comments.

1 Comment

Could you tell me how I concatenate my query with the execute? Because when I do it gives me error EXECUTE FORMAT('COPY (%L) TO %L WITH CSV HEADER',select nombre,dni,edad from test where id=i, 'C:\Users\Usuario\Documents\user'+i+'.csv');
0

You could use dynamic SQL with EXECUTE instead,like this

statement :='COPY (select nombre,dni,edad from test where id=' || i || ') to ''C:\Users\Usuario\Documents\user' || i ||'.csv''';
EXECUTE statement;

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.