1

I can use the -v v1=foo syntax just fine for queries in my sql script, but I can't figure out how to use that parameter in a copy statement. I'd like to execute the script like:

psql -d my_db -f ./exports.sql -v v1="'/Users/username/test.json'"

And in the script do some version of:

copy (
 select * from bar     
) to :v1;

or

DO $$ 
BEGIN
  EXECUTE
   'copy (select * from bar) to ' || :v1;
END $$

or

DO $$ 
BEGIN
  EXECUTE
   format('copy (select * from bar) to %L',:v1);
END $$

But none of the above work :(

1 Answer 1

2

Variable substitution doesn't work in a string literal.

Use psql's \gexec:

SELECT format(
          $$copy (select * from bar) to %L$$,
          :v1
       ) \gexec
Sign up to request clarification or add additional context in comments.

6 Comments

THANK YOU! That definitely works. Finally I have a way to not hardcode the export paths for copy
I'm getting stuck again when I try to use %L value concatenated with a string, what's the proper way to do that? As in COPY ... FROM %L||'myfile.csv' ?
Sounds like a new question.
It's still passing parameters to copy in a script executed from psql, or am I missing something larger than that?
Comments are not for follow-up questions. Please ask a new one.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.