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

  • 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy