1

I have a set of sql files

file1.sql
file2.sql
....

that contain table inserts INSERT INTO <tablename> (...) VALUES (....); in a directory. I would like to add a command into a existing batch file so that it iterates over each file. Currently I use the command

<postgreSQLCommandWithParameters> -U <user> -d <database> -f <pathToSQL>\complete.sql -q

I looked into a for loop but I missing the parameter to point to the correct directory.

for %%G in (*.sql) do <postgreSQL> -U <user>  -d <database>  -E -i"%%G"

Therefore how can I use a for loop to iterate over all sql files which contain insert commands? As a side question: And what is the syntax in the for loop in batch scripts?

A.Dumas
  • 2,619
  • 3
  • 28
  • 51
  • you did not mention shell – Vao Tsun Mar 24 '17 at 14:46
  • You could try to use Powershell. Check this answer (http://stackoverflow.com/questions/3204274/importing-sql-file-on-windows-to-postgresql) – Rigerta Mar 24 '17 at 14:52
  • Also look here. Specific question on how to loop through files in powershell. http://stackoverflow.com/questions/18847145/loop-through-files-in-a-directory-using-powershell – VynlJunkie Mar 24 '17 at 16:51
  • I think this already has an answer. Check this out [http://stackoverflow.com/questions/31537204/execute-several-sql-files-in-a-single-transaction-using-postgresql-and-bash](http://stackoverflow.com/questions/31537204/execute-several-sql-files-in-a-single-transaction-using-postgresql-and-bash) – Kaviranga Mar 27 '17 at 10:14

1 Answers1

0

So I used the following command

FOR /F "tokens=4 USEBACKQ" %%F IN (`dir <pathToSQLFiles> ^|  findstr .sql `) DO (

        <postgreSQL>  %1 -U <user> -d <database> -f  <pathToSQLFiles>\%%F -q

    )   

And here are some cliffnotes

  • "tokens=4 USEBACKQ" takes the numbered items to read from each line and also includes names with space in them
  • ^| findstr .sql filters all SQL files
A.Dumas
  • 2,619
  • 3
  • 28
  • 51