Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a sqlcmd output to a batch variable?

I'm trying to set the output of a sqlcmd query to a variable in a batch file.

Here's my query:

sqlcmd -S <SERVER> -d <DATABASE> -Q "select max(Column1)+1 from Table1"

This gives me exactly what I would expect and what I want:

-----------
         10
<1 rows affected>

However, when I try to set it to a variable, I used this script:

for /f %%a in ('sqlcmd -S <SERVER> -d <DATABASE> -Q "select max(Column1)+1 from Table1"') 
    do set ColumnVar=%%a
echo %ColumnVar%
pause

This gives me this result instead: <1 rows affected> I'm guessing this is because the loop is setting the variable to the last line. So is there a way I could use tokens and delims to parse out the 10 instead?

like image 793
David Avatar asked Dec 23 '14 16:12

David


People also ask

Can you use variables in batch files?

When creating batch files, you can use set to create variables, and then use them in the same way that you would use the numbered variables %0 through %9. You can also use the variables %0 through %9 as input for set. If you call a variable value from a batch file, enclose the value with percent signs (%).

What is Sqlcmd variable?

SQLCMD is not just a script execution tool. It gives us access to internal variables and commands that we can use to automate code execution in SQL Server.

What is Sqlcmd command?

The sqlcmd utility is a command-line utility for ad hoc, interactive execution of Transact-SQL statements and scripts and for automating Transact-SQL scripting tasks. To use sqlcmd interactively, or to build script files to be run using sqlcmd, users must understand Transact-SQL.


1 Answers

Try turning on NOCOUNT:

for /f %%a in ('sqlcmd -S <SERVER> -d <DATABASE> -Q "SET NOCOUNT ON; select max(Column1)+1 from Table1"') do set ColumnVar=%%a
echo %ColumnVar%
pause
like image 187
Dave.Gugg Avatar answered Sep 21 '22 00:09

Dave.Gugg