SQLCMD 的返回值 [英] Return value of SQLCMD
问题描述
我需要检查通过 SQLCMD 实用程序运行的查询的退出状态(成功/失败).例如,我连接的服务器没有有一个数据库名称EastWind
.然后,下面的命令失败并显示消息 ...
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
> echo %errorlevel%
0
我看到两种情况下的返回值是相同的.如何在 SQLCMD
中检查命令是否失败?
I see that the return value is the same in both the cases. How can I check if a command has failed in SQLCMD
?
推荐答案
您需要使用 -V
选项
You need to use the -V
option
注意:这是大写的-V
,而不是小写的-v
.
Note: That's a capital
-V
, not a lowercase-v
.
示例:
> SQLCMD.EXE -S whatever -E -V16 -Q "USE does_not_exist"
Msg 911, Level 16, State 1, ...
Could not locate entry ...
> echo %ERRORLEVEL%
16
更新: 或者,您可以使用 -b
选项,它对执行具有不同的语义(整个批处理在第一个错误时停止).天啊.
Update: Alternatively, you can use the -b
option, which has different semantics to the execution (the whole batch stops on the first error). YMMV.
示例:
> SQLCMD.EXE -S whatever -E -b -Q "USE does_not_exist"
Msg 911, Level 16, State 1, ...
Could not locate entry ...
> echo %ERRORLEVEL%
1
您也可以结合使用 -b
和 -V
.
You can also combine -b
and -V
.
这篇关于SQLCMD 的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!