SQLCMD – How to Use Dynamic Parameters for Connection

sql serversqlcmd

In SSMS I have this

:SETVAR DBSrvrInst MyDatabase
:connect  ADMIN:$(DBSrvrInst)

In the Messages tab I get

Connecting to ADMIN:$(DBSrvrInst)…

The variable isn't being replaced.
But if I do this and remove the constant

:SETVAR DBSrvrInst MyDatabase
:connect  $(DBSrvrInst)

In the Messages tab I get

Connecting to MyDatabase…

The variable is replaced correctly.
How do I get this to work

:SETVAR DBSrvrInst MyDatabase
:connect  ADMIN:$(DBSrvrInst)

I would even be ok with using the port but that doesn't work either

:SETVAR DBSrvrInst MyDatabase
:connect  $(DBSrvrInst),1434

Any suggestions are greatly appreciated.

Best Answer

How about just placing the ADMIN: text in the variable? eg

:setvar DBSrvrInst ADMIN:.\sql2014

:connect $(DBSrvrInst)
GO