paddingtonMike
paddingtonMike

Reputation: 1603

How to indicate in postgreSQL command in which database to execute a script? (simmilar to SQL Server "use" command)

I have the following problem, I need to put in a script that is going to run before the new version is rolled the SQL code that enables the pgAgent in PostgreSQL. However, this code should be run on the maintenance database (postgres) and the database where we run the script file is another one.

I remember that in SQL Server there is a command "use " so you could do something like:

use foo

-- some code

use bar 

-- more code

is there something similar in PostgreSQL?

Upvotes: 23

Views: 50223

Answers (5)

panos
panos

Reputation: 331

You can put in your file something like:

\c first_db_name
select * from t; --- your sql
\c second_db_name
select * from t; --- your sql
...

Upvotes: 17

paddingtonMike
paddingtonMike

Reputation: 1603

well after looking on the web for some time I found this which was what I need it http://www.postgresonline.com/journal/archives/44-Using-DbLink-to-access-other-PostgreSQL-Databases-and-Servers.html

Upvotes: 2

Kuberchaun
Kuberchaun

Reputation: 30324

PostgreSQL doesn't have the USE command. You would most likely use psql with the --dbname option to accomplish this, --dbname takes the database name as a parameter. See this link for details on the other options you can pass in you will also want to check out the --file option as well. http://www.postgresql.org/docs/9.0/interactive/app-psql.html

Upvotes: 1

Scott Bailey
Scott Bailey

Reputation: 8286

You can't switch databases in Postgres in this way. You actually have to reconnect to the other database.

Upvotes: 3

Neall
Neall

Reputation: 27124

Are you piping these commands through the psql command? If so, \c databasename is what you want.

psql documentation

Upvotes: 3

Related Questions