1

Is there a way in SQL to import ALL csv contained in a directory to my postgres table ?

Thank you for your help.

4
  • 1
    Possible duplicate question stackoverflow.com/questions/18533625/… Commented Feb 8, 2014 at 15:54
  • This isn't very helpful Commented Feb 8, 2014 at 16:16
  • Merge files into one and then import. For files without header run this in cmd: copy *.csv all.txt Commented Feb 8, 2014 at 19:49
  • This is usually a feature of the SQL client you use, not of the database server. Commented Feb 9, 2014 at 10:52

1 Answer 1

2

This isn't PostgreSQL specific at all. You need to use a loop to invoke psql once per file, generate a master file that contains \include commands for each input file, or concatenate all the input files and then run them.

All of these tasks are done with the operating system command prompt tools, they're not to do with PostgreSQL.

To concatenate the files and run the result:

type *.sql | psql

To loop over them using cmd.exe's amazingly, incredibly ugly for loop syntax (untested, see How to loop through files matching wildcard in batch file and Iterate all files in a directory using a 'for' loop for details):

FOR %%f IN (*.sql) DO (
  echo %%~nf
  psql -f %%~nf
)

I'm sure the 3rd way is possible too. This might work (the equivalent works in a real shell on a unix box) but is untested as I don't have Windows conveniently to hand:

FOR %%f IN (*.sql) DO (
  echo "\include %%~nf"
) | psql

As far as I know none of these guarantee that the files are run in any particular order. You'd need to look up the documentation on the Windows shell.

Personally - I recommend doing this sort of thing in Powershell, or in Perl or some other less awful scripting language than the cmd.exe batch language.

Either way, all the files must have the system default 1-byte text encoding or must contain an explicit SET client_encoding= ... statement.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.