I want the output of an SQL query Select count(*) from Table to be used as a variable in a Batch script. I am using sqlcmd to execute this query, but haven't figured out how to do this properly.
Any help or examples would be appreciated.
Here is solution I used to get output from query in a batch script variable. This is used in a windows .cmd batch script file. Basically it outputs to a temp file and then extracts the text into a variable.
sqlcmd.exe <SERVER & DB OPTIONS> -h-1 -Q "SET NOCOUNT ON; SELECT COUNT(*) FROM Table" -o output.txt
set /P recCount= < output.txt
echo %recCount%
del output.txt
Notice the use of the -h-1 flag (which tells SQLCMD to suppress column headings in the output) and NOCOUNT within in the SQL command (to suppress the count of rows affected). Also if the query was being made for a string you may want to use the -W parameter to remove trailing spaces from the output.