Question

I'm trying to set up a batch script that basically runs a SQL statement against a database, and if the script returns results it will follow some logic.

Is there a way to have SQLCMD actually return the number of rows it found, or something similar?

I see that I can have the output displayed on the screen or a file, but is there a way to have it put it into a variable so I can have the script evaluate the variable? For example:

SQLCMD -q "select count(*) from active_connections" -r @varactive
IF @varactive > 0 THEN
    <do things>
ELSE END

Or would I need to switch to Powershell to handle this sort of logic?

Was it helpful?

Solution

While @Gary is technically correct that the only thing returned is the ERRORLEVEL, sqlcmd does also display its results to STDOUT. Armed with that, you could do something like this in a batch file:

set SERVERNAME=yoursqlserver
for /f "skip=2" %%x in ('sqlcmd -S %SERVERNAME% -Q "select count(*) from active_connections" ^| findstr /v /c:"rows affected"') do set COUNT=%%x
echo There are %COUNT% records in the active_connections table.

OTHER TIPS

See Docs for sqlcmd and you will see quite a few options you probably never paid attention to.

The only thing an executatble "returns" to the batch script environment is the ERRORLEVEL. For SqlCmd you need the -b option to set this (based on the sql server error level)

If you use the -m option, you can control the error messages send to stdout -- I can't test at the moment, but I think this include the rows affected message (a level 0 error perhaps). You would then have to parse this too (ugly in batch scripts)

This sounds like a real kludge at best to be, you are likely better off to use a better scripting environment. PowerShell, Perl, Python, etc. all more powerful and you can find plenty of examples on-line.

Batch is best when you have a "no-deployment" requirement or you needs are simple. Easy to hit the wall as needs change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top