I want to give the the option to specify some variables on the command-line for my psql-scripts with.
psql -v myVar=myValue
However I found no way to give those variables default values within the sql-script itself. The syntax:
`\set MyVar defaultValue`
overwrites the value myValue
specified on the psql command-line unconditionally.
Is there any way to check if a variable is set within psql?
Setting default values for variables is not supported in psql, but you can do it using a workaround.
This psql command:
does nothing if the variable was already set via psql (this means, myVar is set again to his value), otherwise the variable is set literally to the string
:myVar
.Using this circumstance and the other psql command
\gset
, you can actually set a default value for myVar. Put this on the top of you sql script:It seems to work only with text variables, but you can cast to numeric if you need numeric variables:
How does \gset work:
\gset
allows you to set a variable from the result of a select query. The result variable is named like the column name, this is why you need the clauseAS "myVar"
at the end of the query (don't forget the double quotes if you want to use variables names with uppercase letters).For example the command:
sets the variable
var1
tohello
, the same asSee here for more infos: http://www.postgresql.org/docs/9.4/static/app-psql.html