0

I've got the following batch script for executing sql scripts contained in many files, using sqlcmd utility:

@echo off
setlocal enabledelayedexpansion
set /p servername=Enter DB Servername :
set /p dbname=Enter Database Name :
set /p spath=Enter Script Path :
set /p usr=Enter the username :
set /p pw=Enter the password :
set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
set logfilepath= %spath%\output_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.log
set cmd='dir "%spath%\*.sql" /b'
FOR /f "delims=" %%f IN (%cmd%) DO (
    echo ******PROCESSING %%f FILE******
    echo ******PROCESSING %%f FILE****** >> %logfilepath%
    SQLCMD -S%servername% -U%usr% -P%pw% -d%dbname% -s"  -i%%f -b >> %logfilepath%
    IF !ERRORLEVEL! NEQ 0 GOTO :OnError
)
GOTO :Success

When I run this script a prompt with "1>" will wait for command. I can understand what is going wrong.

Thank you very much

1 Answer 1

2

You are getting SQLCMD started and not doing what you desired. For starters I would change this line

    SQLCMD -S%servername% -U%usr% -P%pw% -d%dbname% -s"  -i%%f -b >> %logfilepath%

to

SQLCMD -S %servername% -U %usr% -P "%pw%" -d%dbname% -s ^"  -i "%%f" -b >> "%logfilepath%"
  1. Not sure if spaces I added are required, but easier to read
  2. Use quotes in case there are poison characters or spaces in password, filename, and path
  3. Escape the column separator ("). This is probably what is causing your problem.
Sign up to request clarification or add additional context in comments.

1 Comment

You are welcome. FYI, I meant to add a space after -d% too. Also, beware that checking the error level after SQLCMD is not doing much for you. It only verifies that you were able to launch SQLCMD... it does not provide any result as to the status of the SQL commands run by SQLCMD. For that you need to parse the contents of the log file that you directed the results to.

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.