问题
If I'm using sqlcmd
in a batch script, can I reference a batch variable inside the query?
So that if I do something like
for /f "delims= " %%a in ('sqlcmd -S SERVER -d DATABASE -Q
"SELECT Column1 FROM Table1 WHERE Column1=[specific number]"') do set var1=%%a
how could I do something like this?:
for /f "delims= " %%b in ('sqlcmd -S SERVER -d DATABASE -Q
"SELECT Column2 FROM Table1 WHERE Column2=[var1]"' do set var2=%%b
So that the WHERE
condition in the second sqlcmd
statement is using the variable set in the first statement?
回答1:
Change Column2=[var1] to Column2=%var1%
回答2:
You can pass arguments from the environment to sqlcmd by using the -v switch and referencing the parameters in your sql statement by the $(variable) syntax. E.g. in your second statement :
for /f "delims= " %%b in ('sqlcmd -S SERVER -d DATABASE -Q
"SELECT Column2 FROM Table1 WHERE Column2=$(var1)" -v var1=%var1%' do set var2=%%b
来源:https://stackoverflow.com/questions/32227390/sqlcmd-using-batch-variable-in-query