Editing SQLCMD Scripts in the Transact-SQL Editor
When you write or edit scripts in the Transact-SQL (T-SQL) editor, you can use a mix of T-SQL and SQLCMD commands if you first enable SQLCMD mode. For more information, see How to: Enable SQLCMD mode in the Transact-SQL Editor.
If you want to include SQLCMD commands and T-SQL commands in the same script, you must ensure that the script conforms to the following requirements:
You must place SQLCMD commands as the first statement on a line.
You cannot place more than one SQLCMD command on each line.
You can precede SQLCMD commands by comments or white space.
You can use comment characters to prevent SQLCMD commands from being executed.
You must use two hyphens at the start of a line to form each single-line comment character.
You must place a colon before each SQLCMD command to clearly distinguish it from T-SQL commands.
You can use environment variables and variables that are defined as part of a SQLCMD script, but you cannot use built-in SQLCMD variables.
You can use the following commands:
Examples
To connect to an instance, instance1, of SQL Server, myserver, by using integrated security, you would include the following command:
:connect myserver\instance1.
To connect to the default instance of myserver using scripting variables, you would include the following command:
:setvar myusername test
:setvar myservername myserver
:connect $(myservername) $(myusername)
To execute a simple query stored in the selectFromTable.sql file in C:\Files, you would include the following command:
:SETVAR tablevar Suppliers
:r C:\Files\selectFromTable.sql
GO
:SETVAR tablevar Customers
:r C:\Files\selectFromTable.sql
GO
The selectFromTable.sql file contains the following example query:
SELECT * FROM $(tablevar)
GO