SQLCMD mode allows running Transact-SQL statements and Windows system commands in the same script. This provides benefits like easily executing scripts across different servers by switching connections, keeping database code and workflows together in source control. Some things to remember when using SQLCMD mode are that IntelliSense and debugging are disabled, the editor cannot respond to OS prompts, and SQLCMD commands always execute before TSQL statements in a batch.
3. Switching between Explorer / command line Small but irritating What is server IP ? Is folder exists ? Is file there ? Ping server Create folder Delete files Rename or copy files
4. Script executions on different servers Create staging table on Staging Server Create fact table on Datawarehouse Change connection Add indexes to some other server
5. Adding database code to source control Take procedures one by one Save to source control What if there are more than 100 procedures?
6. Moving procedure code to production Open file from SourceSafe Execute in Management Studio What if there are more than 100 procedures?
7. Backup & Restore Backup DB Create folder on destination server Copy backup file to destination server Restore DB
8. SQLCMD mode: T-SQL Statements Windows System Commands + in the same script !
11. Writing and Editing SQLCMD Scripts Rules SQLCMD commands must be the first statement on a line. Only one SQLCMD command is permitted on each line. SQLCMD commands can be preceded by comments or white space.
12. Lessons learned Some stuff to remember Enabling SQLCMD mode turns off IntelliSense and the Transact-SQL debugger The Query Editor cannot respond to operating system prompts When using :r command, keep one empty line between each execution ( concatenation ) SQLCMD commands always execute before any TSQL commands in the batch.
13. Lessons learned Some stuff to remember :connect it's not treated as an implicit batch separator. If you forget to put in GO all over the place, ALL the commands are executed against the last server. Line number in error output does not count the lines where SQLCMD commands and variables used SSMS uses Microsoft .NET Framework SqlClient for execution in regular and SQLCMD mode SQLCMD command line uses the OLE DB provider. Because different default options may apply, it is possible to get different behavior while executing the same query in SQL Server Management Studio SQLCMD Mode, and in the SQLCMD utility.
14. Bottom line Execute CMD and T-SQL in one tool. Easy script executions Easy connection switches Keep it in the source control together with all other workflows