Search code examples
mysqlbatch-filesqlcmd

Using batch variable in sqlcmd query


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!


Solution

  • 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.