Marcello Miorelli
Marcello Miorelli

Reputation: 3678

save the result of a operation into a variable within a .BAT file

I have the following BAT file working ok: it connects to an specific sql server and select getdate()

what I really wanted is to test whether the server is connectable.

I would like something like:

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

is there any way I could achieve this?

thanks and regards marcelo

@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

Upvotes: 0

Views: 127

Answers (1)

James L.
James L.

Reputation: 9453

It is easy to run a query and set the result to a DOS environment variable. For instance, you can do the following to get the date/time from the SQL Server instance (SQL Server is running locally in my instance):

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

However, the is_connectable environment variable set in this example will have an arbitrary value, which will make it hard to evaluate. Since you are just trying to verify that the SQL Server is there, alive, and responsive, you should run a query that creates a more predictable output, like this:

@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

Upvotes: 1

Related Questions