Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scripting 将操作结果保存到.BAT文件中的变量中_Scripting_Batch File_Return Value - Fatal编程技术网

Scripting 将操作结果保存到.BAT文件中的变量中

Scripting 将操作结果保存到.BAT文件中的变量中,scripting,batch-file,return-value,Scripting,Batch File,Return Value,我有以下BAT文件工作正常: 它连接到特定的sql server并选择getdate() 我真正想要的是测试服务器是否可连接 我想要一些像: set is_connectable = call sqlcmd.exe %%SERVITORE%% 我有没有办法做到这一点 谢谢和问候 马塞洛 运行查询并将结果设置为DOS环境变量很容易。例如,您可以执行以下操作从SQL Server实例获取日期/时间(SQL Server正在我的实例中本地运行): 但是,本例中设置的是可连接的环境变量将具有任意值,

我有以下BAT文件工作正常: 它连接到特定的sql server并选择getdate()

我真正想要的是测试服务器是否可连接

我想要一些像:

set is_connectable  = call sqlcmd.exe %%SERVITORE%%
我有没有办法做到这一点

谢谢和问候 马塞洛


运行查询并将结果设置为DOS环境变量很容易。例如,您可以执行以下操作从SQL Server实例获取日期/时间(SQL Server正在我的实例中本地运行):

但是,本例中设置的
是可连接的
环境变量将具有任意值,这将使其难以计算。由于您只是尝试验证SQL Server是否存在、是否处于活动状态以及是否响应,因此应运行一个查询,以创建更可预测的输出,如下所示:

@echo off

:: Make sure the variable is undefined to start with
set is_connectable=

:: Make the connection and run a query that should always return '1'
for /f "skip=2 delims= " %%i in ('sqlcmd -S localhost -E -Q "set nocount on; select 1 as [Rows] into #temp; select @@rowcount as [Rows]; drop table #temp"') do set is_connectable=%%i

:: Verify if SQL Server is avaialble
if not defined is_connectable goto NotFound
if "%is_connectable%"=="1" goto Found
goto UnknownError

:Found
echo SQL Server was found and returned '1' as expected...
goto TheEnd

:NotFound
echo SQL Server was not found...
goto TheEnd

:UnknownError
echo SQLServer was found, but the return value was '%is_connectable%' instead of '1'...
goto TheEnd

:TheEnd

如果您只想测试可达性,那么如果实用程序失败,您可能(我已经测试过)可以使用-b选项返回errorlevel=1。来源:-错误报告选项。(这不回答您的原始问题,因此仅作评论)
for /f "skip=2 delims=" %%i in ('sqlcmd -S localhost -E -Q "set nocount on; select getdate() as [Now]"') do set is_connectable=%%i
@echo off

:: Make sure the variable is undefined to start with
set is_connectable=

:: Make the connection and run a query that should always return '1'
for /f "skip=2 delims= " %%i in ('sqlcmd -S localhost -E -Q "set nocount on; select 1 as [Rows] into #temp; select @@rowcount as [Rows]; drop table #temp"') do set is_connectable=%%i

:: Verify if SQL Server is avaialble
if not defined is_connectable goto NotFound
if "%is_connectable%"=="1" goto Found
goto UnknownError

:Found
echo SQL Server was found and returned '1' as expected...
goto TheEnd

:NotFound
echo SQL Server was not found...
goto TheEnd

:UnknownError
echo SQLServer was found, but the return value was '%is_connectable%' instead of '1'...
goto TheEnd

:TheEnd