P
P
poxgsouv2020-11-05 10:25:10
PostgreSQL
poxgsouv, 2020-11-05 10:25:10

How to set denote a variable in a postgreSQL loop?

I'm trying to draw a script where selects are iterated in a loop, but SQL perceives the variable i as the name of a column, how to designate it correctly?

DO
$do$
DECLARE
   a bigint[] := array[1,2,3];
   i bigint; 
BEGIN
   FOR i IN a
   LOOP
      COPY (select column_1 where column_2 = i) TO PROGRAM  'cat >>/tmp/file.csv' (format CSV);
   END LOOP;
END
$do$;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2020-11-05
@poxgsouv

Not directly. COPY does not know parameters, including those inside its possible select.
You need dynamic sql, collect the text of the copy command as exactly the text and execute it:

EXECUTE format($$
   COPY (
       select %L
   )
   TO '/tmp/file';
$$, my_var);

PS: TO PROGRAM to cat instead of directly copy to file - do you have any rational reason?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question