0

Hi All I am Writing a Batch Script Which has to read a set of SQL Files which exists in a Folder then Execute Them Using SQLCMD utiliy.

When I am Trying to execute it does not create any output file. I am not sure where I am wrong and I am not sure how to debug the script. Can someone help me out with script?

@echo off

FOR %F IN (C:\SQLCMD*.SQL) DO sqlcmd -S LENOVO-C00 -U yam -P yam!@ -i %F -o C:\SEL.txt -p -b

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

:Success echo Finished Succesffuly exit /B 0 goto end

:get_error echo step Failed exit /B 40

:end
2
  • if not [%errorlevel%] ==[0] should be if errorlevel 1. Avoid using the pseudo-variable unless you have to since it can break. Commented Aug 24, 2010 at 6:20
  • It should be noted that it isn't necessary to keep your sql scripts in separate files. You can put the entire SQL statements inside the batch file and make them very human readable by using line separators with the carrot character and delayed expansion enabled. Commented Jan 13, 2012 at 0:01

3 Answers 3

1

If this is actually in a batch file (not being executed by hand at the command line), then the %F variables need to have the % characters doubled-up because of the way that cmd.exe executes the lines read from the batch file:

FOR %%F IN (C:\SQLCMD*.SQL) DO sqlcmd -S LENOVO-C00 -U yam -P yam!@ -i %%F -o C:\SEL.txt -p -b

Though I would have thought you'd get a

F was unexpected at this time.

error if you only had one % character in front of the variable name.

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

2 Comments

Hi Michael Thanks for the Reply.After Adding the %% I was able to Run the batch file. But the script was not able to loop or iterate the file's.
Anoop - comment out the "@echo off" so you can see exactly what commands the for command is trying to execute. That may give you a clue to what's going wrong. Alternatively, change the "DO sqlcmd ..." to "DO echo sqlcmd ..." to maybe help debug what's going on.
1

Try to right click the Batch File and run as administrator.

Comments

0

Seems like the answer would be more like this:

FOR %%F "usebackq" IN (`dir.exe C:\SQLCMD*.SQL`) DO ... 

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.