0

我有以下 BAT 文件工作正常:它连接到特定的 sql 服务器并选择 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
4

1 回答 1

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
于 2013-02-12T16:20:56.237 回答