5

I'm trying to use a DOS command prompt on Server 2012R2 to run a batch with the following in it. I want to run a SQL command (sqlcmd) and return the results to the command window.

This is what I'm currently trying but sqlcmd keeps throwing back Sqlcmd: 'test': Invalid argument. Enter '-?' for help.20:56:08.

FOR /F "tokens=* USEBACKQ" %%F IN (`sqlcmd -S localhost -E -i "backup.sql" -v dbname="test"`) DO (
    Echo %%F
)

However if I try it without params/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, DOS CMD, as well as a FOR /F loop such as in my first example?

2

In your command that works, you don't have an equal sign (=). When you run the command that fails and look at the output, you should notice the equal sign disappears. That's because that character needs to be escaped with a caret. (in my example below, notice the caret before the equal sign)

Try:

FOR /F "tokens=* USEBACKQ" %%F IN (`sqlcmd -S localhost -E -i "backup.sql" -v dbname^="test"`) DO (
    Echo %%F
)
  • 1
    I didn't even notice that = missing! Next time I see this type of error message I will know what to direct my attention at. Thanks Scott! .... And to think I was defeated by a carrot... – Arvo Bowen Mar 15 '18 at 23:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.