Search code examples
sql-serverbatch-filecmdsqlcmdlogfile

SQLCMD command, How to save output into log file


The following question has helped me solving the problem of executing multiple SQL Scripts located in file. Run all SQL files in a directory However, I did not get how to redirect the output into a separate log file. Someone suggested the following script but since I don't understand it, it did not work and I can't find out the error.

for %f in (*.sql) do sqlcmd /S <servername> /d <dbname> /E /i "%f" >> sql.log 2>&1) 

Solution

  • If you need the output into one common file then you should use the @Abhishek 's answer.

    If you need the output into a separate log file for an each input sql file then you can use -o parameter of sqlcmd command. Your bat file could look like this:

    for %%G in (*.sql) do sqlcmd /S <servername> /d <dbname> -E -i"%%G" -o C:\logs\%%G.log
    pause
    

    In this case for

    1.sql

    2.sql

    you will get:

    1.sql.log

    2.sql.log