Reputation: 3056
I would like to be able to write sql query that changes the database to which I am currently logged in.
Example:
$ psql my_db
psql(9.1.1)
my_db=> ALTER DATABASE my_db SET some_variable = '0';
^^^^^
Is there a way to avoid specifying the database name in this query?
Upvotes: 21
Views: 3733
Reputation: 5355
Combining a few things together, including previous answers and the "\gset" technique mentioned in http://marxsoftware.blogspot.com/2015/08/postgresql-psql-variable-from-query.html, and the most streamlined way is:
-- note no semicolon after \gset:
select current_database() \gset
alter database :current_database set some_var = '0';
Upvotes: 4
Reputation:
If you're on 9.1 you can use:
DO $$
BEGIN
execute 'alter database '||current_database()||' set some_var = ''0''';
END
$$;
Upvotes: 26
Reputation: 66243
If you are executing the script in psql
you can use the substitution mechanism of psql
:
alter database :DBNAME SET ...
The documentation is here: http://www.postgresql.org/docs/current/interactive/app-psql.html#APP-PSQL-VARIABLES
Upvotes: 12