Search code examples
sql-servert-sqlbatch-filedossqlcmd

SqlCmd :connect with variables and backslash


When using SqlCmd to try and connect to an active server I have discovered that these both work:

:connect myServer\myInstanceName -U myLogin -P myPassword

:setvar INSTANCE myInstanceName
:connect $(INSTANCE) -U myLogin -P myPassword

This does not:

:setvar serv myServer
:setvar inst myInstance
:connect $(serv)\$(inst) -U myLogin -P myPassword

It throws this as a syntax error, I suspect because it thinks the back-slash is an escape character.

Doing this doesn't help:

:connect '$(serv)\$(inst)' -U myLogin -P myPassword

And neither does this:

:connect $(serv)\\\\$(inst) -U myLogin -P myPassword

And I can't figure out how sqlCmd is supposed to concatenate variables, so I can't pass the whole thing in as a variable. If you try and set a variable like this:

 :setvar serv myServer
 :setvar myVariable $(serv)\

Then it literally sets myVariable to be "$(serv)\" which isn't a lot of help.

Anyone help?


Solution

  • The best solution I've found to this is to set the variables using powershell or DOS scripts.