This may seem like a trivial “trick”. I thought so too at first, but I’ve found that I use this trick over and over again.
When developing scripts, often times I find myself commenting some blocks of code out, either to explore, to test, to debug, or to simply try out other T-SQL constructs. When you have commented code using the C-style comment, it is easy to select any block of code inside and execute them:
/*
SELECT * FROM sometable;
GO
SELECT * FROM anothertable;
GO
*/
But what if you used SQL Server Management Studio’s (SSMS) single line comment shortcut to comment out parts of your code?
Of course you can use the uncomment shortcut, but that’s still a bit of work. Highlight code, move mouse to SSMS toolbar, click on icon, execute. No I’m not a whiner, I just like doing things more efficiently when possible. Imagine, take that one icon click, and if you do it 10x or 20x in a day, it adds up
What you can do (or try) is to press the ALT key, then highlight the code you want to execute, then execute.
Small trick that saves you one icon click. Seemingly trivial, but believe me, it does make your work faster.
Selecting and Executing Commented T-SQL Code,
I’d give one caution with this – when you comment code with the minus signs, you can have a tougher time reverse engineering the code later when examined through Profiler. If you like to trace your server, then copy/paste the queries out of the trace table or Profiler UI in order to see them in SSMS, the minus signs can hose up the syntax. The copy/paste process doesn’t always honor line breaks, so you end up with one long line of T-SQL and you’re not sure where the remarks begin and end. Playing it safe with the /**/ style of remarks makes it easier to analyze the code later.
That’s an interesting point. I haven’t come across that before but I can totally see it happening one of these days – thanks for the tip!
Very cool tip, thanks.
>>Playing it safe with the /**/ style of remarks makes it easier to analyze the code later.
Using the comment block is not really “playing it safe”. If you run the entire block on SQL2000 you will get something like:
Server: Msg 113, Level 15, State 1, Line 1
Missing end comment mark ‘*/’.
(77865 row(s) affected)
Server: Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near ‘*’.
This is because the GO directive will interrup the comment block. That said 1) you don’t need the GO directives here and 2) I’m guessing you’re all on 2005+ by now anyway.