Skip to content Skip to sidebar Skip to footer

Sqlcmd Utility From Bat File - How To Return Errorlevel In Case Of Syntax Error

How can I get %ERRORLEVEL% from SQLCMD utility when some of .sql files contains syntax error? These files create stored procedures. They don't invoke 'raiseerror', but they can con

Solution 1:

You do need the -b switch but together with enabledelayedexpansion, that way you can use !errorlevel! inside the loop and get the expected results.

Put setlocal enabledelayedexpansion anywhere before you execute sqlcmd, probably best at the beginning of the batch or just before the loop. Also note the use of exclamation points (!) instead of the percent signs (%), which denote the use of delayed expansion.

[I also tested with if not errorlevel 0 … (no !, nor any %: see help if) but I could not get the desired results]

Solution 2:

Thank you, here is the work batch script.

@ECHO OFF
setlocal enabledelayedexpansion
FOR /R "C:\SQL" %%G IN (*.sql) DO (
sqlcmd -S%1 -d tangoDB -E -h-1 -w255 -i "%%G" -b
echo   %%G  -  !ERRORLEVEL!
IF !ERRORLEVEL! NEQ 0EXIT /B !ERRORLEVEL!
)

Post a Comment for "Sqlcmd Utility From Bat File - How To Return Errorlevel In Case Of Syntax Error"