in the above SQL code.
• What is the advantage of using the latter method?
This allows the script to be called from the cmd line tool sqlcmd.exe with variables passed in e.g.
sqlcmd -S localhost -d Master -q "SELECT '$(var1)' as [$(var2)]" -v var1="Mooooo" var2="Cows Say"
and also allows you to use a script against multiple instances using the :connect option
:setvar word "now"
:SETVAR server1 "SERVERNAME01"
:SETVAR server2 "SERVERNAME02"
:connect $(server1)
SELECT @@servername,'$(Word)' as [Word]
GO
:connect $(server2)
SELECT @@servername,'$(Word)' as [Word]
GO
• Is there a way I can use the latter method from outside of SQL Server Management Studio (like when I'm using SQL commands in some app)?
yes using the sqlcmd line as above
• In SQL Server Management Studio, I don't see any indication when SQLCMD Mode is enabled or it's not, so if I forget whether I’ve enabled it, I just have to play with it to find out for myself. Am I missing something? How can I tell?
the :setvar will go grey when enabled