Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to put together a batch file to run a large number of .sql files without doing so individually.

So far I have:

@echo off
echo "Enter Server"
set /p SERVER=

echo "Enter Database"
set /p DATABASE=

del *.log

for /r %%i in (*.sql) do sqlcmd -E -S %SERVER% -d %DATABASE% -i"%%i" -m0 -o"%%i.log" -w500 


This works as far as it goes.

However what I really want to do is route any errors to a separate .err file, so that it is very clear at a glance which of the (100+) files failed.

I saw the :Error parameter, but I'm not sure how to apply it here.

Is there an easy way to acheive this?

share|improve this question
Have you thought about PowerShell instead of SQLCMD? – Aaron Bertrand Jan 26 '12 at 3:13
up vote 6 down vote accepted
for /r %%i in (*.sql) do sqlcmd -E -S %SERVER% -d %DATABASE% -i"%%i" -m0 -w500  -b -r  >%%i.log  2>%%i.err

Not perfect since it creates an empty error output file when there are no errors, but a .err file with > 0 bytes will have the errors.

for %%a in (*.err) do if %%~za==0 del "%%a"

..if that's a problem...

share|improve this answer
That's spot on - thanks for your help. – Jon Egerton Jan 26 '12 at 11:15

You can use sqlsplus (or SQLS*Plus) to execute multiple sql files - check - SQLS*Plus is like an Oracle© SQL*Plus / sqlplus SQL command line tool for Microsoft© SQLServer 2008, 2005 and 2000

  1. execute file like:

@1.sql @2.sql @3.sql

  1. Spool errors:

spool 1.log ... spool off

spool 2.log ... spool off

share|improve this answer
If you are affiliated to this product as it seems you are from your profile, it would be good form to declare that in your answer. – Jack Douglas Jan 31 '12 at 10:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.