1

I have a postgres sql script that has a create table statement. Before that it tries to connect to database using \c dbname inside same script. I want to pass this dbname as parameter to this sql script. If no parameter is passed it needs to assign a default value declared inside the script.

I see parameters can be passed to postgres sql script like eg: psql -v dbname = testdb -h localhost -U postgres -a -f create_table.sql

and variables can be declared inside postgres sql file using eg: dbname VARCHAR := "local_db"; but having trouble how to check if parameter is passed or not and assign default value if it is not passed.

Any idea how to achieve this?

bigdata123
  • 453
  • 2
  • 8
  • 24
  • 1
    Take a look at this one, it may help: https://stackoverflow.com/questions/32582600/only-set-variable-in-psql-script-if-not-specified-on-the-command-line – ravioli Aug 27 '19 at 06:26

1 Answers1

0

You can pass a variable to psql with

psql -v 'var=value'

In the script you can reference the variable as :var. There are also :'var' and :"var" to get quoted versions of the value.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263