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.
By default, this mode is turned off. To enable SQLCMD mode, click the SQLCMD Mode option under the Query menu: Another way to enable the SQLCMD Mode is by using a combination of keys ALT+Q+M from the keyboard. In SSMS, there is an option to set the query windows to be opened in the SQLCMD mode by default.
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%
You can avoid an extra/temporary file, by calling sqlcmd.exe
using the FOR
batch command:
for /F usebackq %%i in (`sqlcmd -E -S "devserver,4711" -h-1 -Q "SET NOCOUNT ON; SELECT COUNT(1) ..."`) do (
set count=%%i
)
if not defined count (
echo Failed to execute SQL statement 1>&2
) else (
echo %count%
)
Some notes:
CMD.EXE
session, i.e. the command line, use %i
instead of %%i
-h-1
option tells sqlcmd.exe
to suppress the column headers, so the output is really only one line of text.sqlcmd
would see server and port as to distinct arguments and fail.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With