SQLCMD utility from BAT file - how to return ERRORLEVEL in case of syntax error

走远了吗. 提交于 2019-12-03 17:24:31

问题


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 conatin syntax error and I need to terminate the process. But it always returns %ERRORLEVEL% as 0. I tried use -b, -V and -m (and their combinations), but nothing worked for me as expected.

Here's the code fragment of my BAT file.

REM process all sql files in "SQL\scripts" folder and subfolders
FOR /R "SQL\scripts" %%G IN (*.sql) DO (
    sqlcmd -d %1 -S %2 -U %3 -P %4 -i "%%G" -b -V 1

    echo %ERRORLEVEL%
    IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
)

回答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]




回答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 0 EXIT /B !ERRORLEVEL!
)


来源:https://stackoverflow.com/questions/5789568/sqlcmd-utility-from-bat-file-how-to-return-errorlevel-in-case-of-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!