I'm trying to use a Windows command prompt on Server 2012 R2 to run a batch file with the following command line. I want to run an SQL command (sqlcmd) and return the results to the console window.
This is what I'm currently trying, but sqlcmd
keeps throwing back:
Sqlcmd: 'test': Invalid argument. Enter '-?' for help.
FOR /F "tokens=* USEBACKQ" %%F IN (`sqlcmd -S localhost -E -i "backup.sql" -v dbname="test"`) DO (
Echo %%F
)
Note: I have also tried to run just this sqlcmd
command (above) in a command prompt with no issues. It's like it does not like the FOR /F
loop or something.
However if I try it without parameters/variables it works perfectly!
FOR /F "tokens=* USEBACKQ" %%F IN (`sqlcmd -S localhost -E -i "backup.sql"`) DO (
Echo %%F
)
Does anyone know a way around getting the variables passed to my SQL query using sqlcmd
, Windows CMD, as well as a FOR /F
loop such as in my first example?
When a line batch code is processed it goes through multiple phases, in a specific order. The order of these phases means that in this case your equals character, =
requires special attention. For a full explanation on these phases read this information.
Here's two methods, one of which was already given in the comment area.
I have formatted the command over three lines so that it's clearer, whether you do that too is optional.
Escape the equals character =
with a caret ^
:
For /F "Delims=" %%A In ('
sqlcmd -S localhost -E -i backup.sql -v dbname^=test
') Do Echo %%A
Or if you wish to doublequote your filename and value:
For /F "Delims=" %%A In ('
sqlcmd -S localhost -E -i "backup.sql" -v dbname^="test"
') Do Echo %%A
Surround the command in doublequotes, "
:
For /F "Delims=" %%A In ('
"sqlcmd -S localhost -E -i backup.sql -v dbname=test"
') Do Echo %%A
For /F "Delims=" %%A In ('
"sqlcmd -S localhost -E -i "back up.sql" -v dbname="my test""
') Do Echo %%A
Please note as shown above, whilst it's probably good practice, Microsoft state, 'File paths that contain spaces must be enclosed in quotation marks' and 'Enclose the value in quotation marks if the value contains spaces'. They were not needed in your case and could have been omitted.