Accessing the returned value of a SQL statement in SQLCMD

batch-file, dos, sql-server, sqlcmd

Solution

You can easily save the result of the execution into a text file, either by using the `-o` sqlcmd flag or by using the standard `>` redirector. You can then format this file by removing the column header (flag `-h`) and removing the rowcount from SQL Server (`SET NOCOUNT ON`).

The following script will generate a file `result.txt` with only the value of `COUNT(1)` and a line break:

SQLCMD -E -S devserver -Q "SET NOCOUNT ON; SELECT COUNT(1) FROM Cases" -h -1 
  > result.txt

And then read the value back with ...

set /p value=< result.txt
echo %value%

Problem

I'm trying to get the value of a SQL statement when I run it in a DOS batch file ... ``` sqlcmd -E -S DEVSERVER -Q "SELECT COUNT(1) as [CaseCount] FROM Cases" ``` I'm not after the error level as in this stackoverflow question, rather I'm after the actual count returned from the database, so I can do some additional logic.

Original source

Related problems