SoFunction
Updated on 2025-03-11

Postgresql psql file execution and batch processing of multiple SQL file operations

Create a new batch file

\encoding UTF8;
\cd C:/Gmind/ddl
\set ON_ERROR_STOP 1
\set ECHO all
\timing on
\i s_product.sql;
\i s_branch.sql;
\i s_comment.sql;
\i s_class.sql;
\i s_drawing.sql;
\i s_dmemo.sql;
\i s_form.sql;

\encoding Set client character set encoding (optional)

\cd Switch directory. Used to switch the command execution directory of psql to the directory where the current file is located

\set ON_ERROR_STOP Set the variable ON_ERROR_STOP (optional), which automatically terminates when an error occurs in the script execution. If not set, the execution will continue by default

\set ECHO all Set variable ECHO (optional) to display the execution script of each step to the standard output

\timing on Turn on the timing function (optional) to calculate the time spent in each step of the script

\i Execute the script file. Directories are backslashes (/) in psql, and the upper directory of the relative path is represented by (..)

Execute, open the cmd window, execute

psql -U postgres -d testdb -f C:\Gmind\ddl\ > C:\Gmind\

Notice:

1. The SQL file format is best for Unix, otherwise there may be errors.

2. If prompted: psql is not an internal or external command, you need to add C:\Program Files\PostgreSQL\10\bin to the environment variable

Additional: PostgreSQL - Run SQL files with psql

For pre-written SQL files, such as /home/user1/, there are two ways to run this SQL file.

Method 1: Execute SQL files after connecting to db

First connect to the corresponding db through psql:

psql -d db1 -U userA

Then enter the password, enter:

\i /pathA/

There is a problem here. If you write the path separator in the path of the SQL file as \, you will report an error saying Permission denied.

The file path here must use the path separator/ under the Linux platform, otherwise an error will be reported.

Method 2: Execute SQL files directly through the psql command

This method does not require logging into the database first, just use one command:

psql -d db1 -U userA -f /pathA/

Then enter the password to execute the SQL file into the corresponding db.

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.