When developing T-SQL code, I frequently have a number of stored procedures created and run inside one .sql file.Â While Iâ€™m generally good at highlighting the single statement I want to run, there are some situations where the highlight is misplaced â€“ usually by me getting complacent with the lack of lag on Remote Desktop.Â Suddenly Iâ€™ll get a dose of lag, my highlight command (shift-uparrow) wonâ€™t be processed, but my Execute (F5) command will.
To defend against this, I determined that the best option would be to create a severe error at the top of the .sql file to ensure that execution would cease.Â Unfortunately, this only stops the execution of the current batch, and as CREATE PROCEDURE must be at the start of the batch, I have many batches in my code.
Five minutes after requesting suggestions from Twitter, Rob Farley suggested using SQLCMD mode â€“ which is a feature that I havenâ€™t used very often.Â This is activated in Management Studio via the â€śQueryâ€ť | â€śSQLCMD Modeâ€ť menu item, and can be specified as the default mode for all new query windows.
Placing the following code at the top of the file results in a fatal error that completely halts execution:
:on error exit SELECT * FROM SomeTableThatDoesntExist GO !!dir GO
The !!dir command will list the contents of the current directory.Â You can run this line by itself, but this line wonâ€™t be executed if you run the entire .sql file.
The drawback to this method is that you lose Intellisense in SQL Server 2008 and the ability to debug your code, but Iâ€™m willing to live with this to prevent having to comment out my more dangerous statements!