0

How can I pass command line args to sql files ran with psql (Postgres)?

i.e.

psql mydatabase < mysqlfile.sql arg1 arg2 arg3...

Is this possible?

1 Answer 1

4

Use variable interpolation feature in psql.

If you specify -v variable1=value1 or --set variable1=value1 parameter on command line, then :variable1 in the sql file will be replaced with corresponding text value.

Note: use standard-SQL quoted strings if you need quotes, spaces and so on.

Example:

echo "SELECT :arg1 FROM :arg2 LIMIT 10;" > script.sql
psql mydatabase -v arg1=relname -v arg2=pg_class < script.sql  
psql mydatabase -v arg1="'some string' as label" -v arg2=pg_namespace < script.sql  
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.