2

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?

1

1 Answer 1

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.

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.