Pass command line args to sql (Postgres)

2019-08-22 09:25发布

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条回答
beautiful°
2楼-- · 2019-08-22 09:53

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  
查看更多
登录 后发表回答