In MS SQL Server, I create my scripts to use customizable variables:
DECLARE @somevariable int
SELECT @somevariable = -1
INSERT INTO foo VALUES ( @somevariable )
I’ll then change the value of @somevariable at runtime, depending on the value that I want in the particular situation. Since it’s at the top of the script it’s easy to see and remember.
How do I do the same with the PostgreSQL client psql?
Postgres variables are created through the \set command, for example …
… and can then be substituted, for example, as …
… or …
edit: As of psql 9.1, variables can be expanded in quotes as in:
In older versions of the psql client:
… If you want to use the variable as the value in a conditional string query, such as …
… then you need to include the quotes in the variable itself as the above will not work. Instead define your variable as such …
However, if, like me, you ran into a situation in which you wanted to make a string from an existing variable, I found the trick to be this …
Now you have both a quoted and unquoted variable of the same string! And you can do something like this ….