0

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?

2 Answers 2

0

Change Column2=[var1] to Column2=%var1%

Sign up to request clarification or add additional context in comments.

5 Comments

Okay so I can still use the same syntax indiscriminately?
The %var1% will be replaced by real value during batch execution.
This batch has some issues you need to be aware. 1). Select may return multiple records. Last value will be assigned to the variable. SELECT TOP 1 may help. 2). Use SET NOCOUNT ON; before the statement, othervise line "(1 rows affected)" will be the last line. 3). If SELECT affect 0 records then last line will be "-----------" an that will be assigned to the variable.
Ah, so it won't return null if there are no results?
No. SQLCMD will not return NULL. It returns message "(0 row(s) affected)"
0

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

2 Comments

Are the parenthesis around var1 i.e. (var1) part of syntax or just implying a placeholder?
They are indeed, the syntax is $(externalVariableName)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.