Search code examples
sql-server-2005batch-filesqlcmd

SQLCMD Usage in Batch file


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

Solution

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