Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

postgresql

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?

like image 535
paddingtonMike Avatar asked Oct 11 '10 18:10

paddingtonMike


People also ask

How do I run a SQL script in PostgreSQL?

Another easiest and most used way to run any SQL file in PostgreSQL is via its SQL shell. Open the SQL shell from the menu bar of Windows 10. Add your server name, database name where you want to import the file, the port number you are currently active on, PostgreSQL username, and password to start using SQL shell.

How do you know which database is being used in PostgreSQL?

Step 1: Log in to the server using the SQL Shell (psql) app. Step 2: Run the following query: SELECT datname FROM pg_database; psql runs the query against the server and displays a list of existing databases in the output.

How do I get SQL script from PostgreSQL?

To generate SQL scripts from your PostgreSQL project click the SQL Script icon on the main toolbar. New modal opens. Click Save Script and select a location where the file should be stored. Option Overwrite existing files allows you to ignore existing scripts and overwrite them without getting a warning.

What is the name of the PostgreSQL command that can run SQL Server from the command line?

psql is a terminal-based front-end to PostgreSQL. It enables you to type in queries interactively, issue them to PostgreSQL, and see the query results. Alternatively, input can be from a file or from command line arguments.


1 Answers

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
...
like image 156
panos Avatar answered Oct 17 '22 04:10

panos