Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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 am trying to execute a Set of SQL scripts using a batch bile. When I try this Windows batch file it doesn't run. Please tell me know how to write the script to loop through the files?

My script:

sqlcmd -S tcp:LENOVO-GH1C00\SAM -U UserName -P PassWord -i c:\SQLCMDSCRIPTS\SELECT.SQL -o C:\SELECT.txt -p -b

IF NOT [%ERRORLEVEL%] ==[0] goto get_Error

echo Finished Succesffuly
exit /B 0
goto end

echo step Failed
exit /B 40

share|improve this question
What happens when you run it? Can you run the sqlcmd step manually at a command prompt and see what happens? – SqlACID Aug 22 '10 at 21:49

You will need to use the FOR statement. At a CMD.EXE prompt type help for for more information.

Here is the general for for iterating over a set of files:

FOR %variable IN (set) DO command [command-parameters]

For your needs you might do something like:

FOR %f IN (c:\SQLCMDSCRIPTS\*.SQL) DO sqlcmd ... -i %f ...

but you'll have to adapt it to fit what you're trying to do and you'll probably have to do the error handling differently.

share|improve this answer

Your Answer


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