SQLCMD using batch variable in query

人走茶凉 提交于 2019-12-25 07:03:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!