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

时间:2013-02-12 13:03:59

标签: scripting batch-file return-value

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

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

我想要像:

set is_connectable  = call sqlcmd.exe %%SERVITORE%%

有什么方法可以实现这个目标吗?

感谢和问候 马塞洛

@echo off
color fc
cls
echo.
@ECHO --- BEGIN THE SCRIPT 1 ----
echo.
@echo the SERVITORE is "%1"
echo.
echo.

if "%1"=="" GOTO USAGE


set SERVITORE=-Stcp:%1% -Q " USE MASTER select getdate() "

call sqlcmd.exe %%SERVITORE%%


color 6
GOTO THE_END

:USAGE
echo.
echo USAGE:
echo. 
ECHO the first parameter is the SERVITORE server.
echo example 1 SERVITORE108
echo.
ECHO the second parameter is optional 
echo but if not supplied the default is \\SERVITORE\folder2$
echo.

echo ATB
echo.

:THE_END
color 8

1 个答案:

答案 0 :(得分:1)

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

for /f "skip=2 delims=" %%i in ('sqlcmd -S localhost -E -Q "set nocount on; select getdate() as [Now]"') do set is_connectable=%%i

但是,此示例中设置的is_connectable环境变量将具有任意值,这将使其难以评估。由于您只是想验证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