0

I'm trying to create a batch to execute a few sql script and some queries. I use sqlcmd in my batch like this :

@echo off
sqlcmd -S server -U user -P password -Q query

As I will execute different queries on the same server, I'd like to replace the server statement with a variable. So I could write something like this :

@echo off
SET server=192.X.X.X
sqlcmd -S server -U user -P password -Q first query
sqlcmd -S server -U user -P password -Q second query

I found this question on SO but I'm still unable to understand how that works :

SQLCMD using batch variable in query

Does anyone have an idea ?

Thanks a lot!

2
  • Change each instance of -S server to -S %server% Commented Dec 21, 2017 at 16:15
  • Oh gosh, I tried anything but this. I did it like <server> or %server but never like this. Thanks a lot man ! Commented Dec 21, 2017 at 16:18

2 Answers 2

2

Expanding on my comment a little:

@Echo off
Set "server=192.X.X.X"
Set "user=myname"
Set "password=pa55w0rd"
sqlcmd -S %server% -U %user% -P %password% -Q first query
sqlcmd -S %server% -U %user% -P %password% -Q second query

You may wish to enclose your variables with relevant quoting as necessary.

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

2 Comments

And what if I'd like to concat a variable with a string in sqlcmd ? I tried with "sqlcmd -S %server%&"myString" but it's not functional. Is it possible directly in the sqlcmd statement or should I do this concatenation in a SET var=%server%&"myString" in ordre to use it later ?
If you want to join them then just use Set "var=%server% myString" (with or without the whitespace as needed). Additionally if you wish to include an ampersand, & then it will need escaping with the caret, ^ like this Set "var=%server% ^& myString".
0

From Microsoft: "Cmd.exe provides the batch parameter expansion variables %0 through %9. When you use batch parameters in a batch file, %0 is replaced by the batch file name, and %1 through %9 are replaced by the corresponding arguments that you type at the command line."

So if the number of queries you wish to execute is known just pass them in through parameters like this:

Test.bat:

@echo off
SET server=192.X.X.X
sqlcmd -S server -U user -P password -Q %1%
sqlcmd -S server -U user -P password -Q %2%

Then call Test.bat like this:

Test.bat "Select * from Test1" "Select * From Test2"

You can pass up to 9 queries this way.

Comments

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.