Return value of SQLCMD
I need to check the exit status (success/failure) of a query run through SQLCMD utility. For example, the server I am connecting doesn't have a database name EastWind
. Then, the command below fails with the message ...
> "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE"
-S ZEPHIR -E -Q "USE WestWind"
Changed database context to 'WestWind'.
> echo %errorlevel%
0
> "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE"
-S ZEPHIR -E -Q "USE EastWind"
Database 'EastWind' does not exist. Make sure that the name is entered correctly
开发者_Go百科> echo %errorlevel%
0
I see that the return value is the same in both the cases. How can I check if a command has failed in SQLCMD
?
You need to use the -V
option
Note: That's a capital
-V
, not a lowercase-v
.
Example:
> SQLCMD.EXE -S whatever -E -V16 -Q "USE does_not_exist"
Msg 911, Level 16, State 1, ...
Could not locate entry ...
> echo %ERRORLEVEL%
16
Update: Alternatively, you can use the -b
option, which has different semantics to the execution (the whole batch stops on the first error). YMMV.
Example:
> SQLCMD.EXE -S whatever -E -b -Q "USE does_not_exist"
Msg 911, Level 16, State 1, ...
Could not locate entry ...
> echo %ERRORLEVEL%
1
You can also combine -b
and -V
.
I am not sure, but did you tried SQLCMD -m switch? sqlcmd Utility
-m error_level
- Controls which error messages are sent to stdout. Messages that have a severity level greater than or equal to this level are sent. When this value is set to-1
, all messages including informational messages, are sent. Spaces are not allowed between the-m
and-1
. For example,-m-1
is valid, and-m -1
is not.
精彩评论