I have a folder in a directory in my PC which contains multiple SQL files. Each of the file is a Postgres function. I want to execute every SQL file situated in the folder at a time in PostgreSQL server using PgAdmin or in other way. How can I accomplish this?
-
Have you considered merging these files into a single one, which is fairly straightforward, and then executing it? ;)Jim Jones– Jim Jones2022-12-21 11:12:42 +00:00Commented Dec 21, 2022 at 11:12
-
I thought about it but don't know how to do. I want a process by which I can execute all SQL files in PostgreSQL server. There are 500+ sql files. Currently I have to execute each sql file individually. This is too time consuming.Alien– Alien2022-12-21 11:17:25 +00:00Commented Dec 21, 2022 at 11:17
Add a comment
|
1 Answer
I apologize if I'm oversimplifying your question, but if the main issue is how to execute all SQL files without having to call them one by one, you just need to put them in a loop, e.g. in bash calling psql
#!/bin/bash
for f in *.sql
do
psql -h dbhost -d db -U dbuser -f $f
done
Or cat them and pipe the result to psql stdin:
$ cat /path/to/files/*.sql | psql -h dbhost -d db -U dbuser
And if you need them to run in a single transaction, consider merging the SQL files, e.g. using cat - this assumes all statements in your sql file are properly terminated:
$ cat /path/to/files/*.sql > merged.sql
17 Comments
Alien
where to execute the command? Is this solution for windows? My OS is windows..
Jim Jones
@Alien those are linux commands. Look for the equivalent on Windows (
cat -> type?). I haven't touched Windows in ~20 years.Alien
where to execute the command? In CMD?
Jim Jones
@Alien yes, in the command line terminal of Windows. There is certainly a way to emulate bash commands using windows though: geeksforgeeks.org/use-bash-shell-natively-windows-10
Alien
and the CMD should be opened under the bin folder where PostgreSQL is installed? like
C:\Program Files\PostgreSQL\15\bin? |