Commenting your Code

You should always add descriptive comments to any code that will live longer than a single event. It's useful not only for the other unfortunate souls blessed with your code, but for yourself, years later, when you say "what was I thinking here?" I've recently had to debug some code and it is IRRITATING to follow without knowing what on earth this person was thinking. Not that I'm upset or anything. I'm just sayin'.

At the top of your code, you should have a "Comment Block" that describes what the code does, who wrote it, and what changes have been made. Like this:

 /* 
 Title: 002 - Setup SQLCMS.sql
 Purpose: Setup the various components for SQL CMS
 Version: 1.1
 Modification History:
 04/30/2009 - Buck Woody - Initial Script Creation
 05/15/2009 - Buck Woody - Added MAPS load scripts
 Replacement Parameters: (Press CTRL-SHIFT-M To use)
  
 Requirements: 
 1. SQL Server 2008
 2. A database to hold these values. 
  
 Optional: 
 1. The Management Data Warehouse feature from SQL Server 2008 to be installed. Enter the name of the MDW database
 you create as the "Storage_Database" value.
  
 2. The Microsoft Assessment and Planning Tool installed and configured. Copy over the database creates from the MAPS
 tool and run the usp_transfer_MAPS_data stored procedure. 
 */

You should also comments lines where you had to do something..."interesting".

 /* I didn't want to have to drop this table, but I didn't see a way around it - I needed to persist the state of the data so a global temp wouldn't work */
  
 DROP TABLE mytable 

You'll notice that I use "block comments" or this: /*  and */. I do this on purpose - you can use two dashes: -- at the start of a line, but it then depends on a linefeed character, which might get copied out. Something like this could happen:

 -- Whatever you do, don't type DROP TABLE mytable

And that gets copied wrong or someone presses an enter key, and then this happens:

 -- whatever you do, don't type
 DROP TABLE mytable

So this is better:

 /* This will always be safe. */
  
 /* This will
                 always be 
  
 safe */
  
 /* This
 will
 always 
 be 
 safe */

 

Also - if you're creating a stored procedure, don't do this:

 /* This is a really cool stored procedure */
 CREATE PROC testme
 AS
 SELECT @@VERSION

Instead, do this:

 CREATE PROC testme
 AS
 /* This is a really cool stored procedure */
 SELECT @@VERSION

Then the comments will stay with the stored proc.