Technical Article

The case against using single-line comments

,

This isn't a "script" per se - but rather an observation about a common issue in writing scripts.

I want to alert SQL programmers to the issues surrounding the use of single-line comments.  I try to avoid these whenever possible, and use block comments instead (except, of course, when commenting out the keyword GO).

The reason is that, if a script is copied into a text editor that "wraps" lines, some single-line comments could be broken up into multiple lines.  If one were to copy that code from the editor into Query Analyzer and execute it, the result will be a syntax error, or in the worst case scenario, the execution of dangerous and unwanted code.

I've actually seen this happen with scripts submitted to SQLServerCentral.com.  The text box wherein scripts are pasted on this site "wraps" the text, and I've seen several where single-line comments were broken up into multiple lines.

Below, I have written a couple of examples to illustrate the importance of this:
 

/* Example 1: using single-line comments */
USE PUBS
GO

/*
This script will select the contents of the Authors table into a temp table.  Then it drops the Authors table.
*/
--Make sure you execute the following statement before you
drop table Authors

/*
Oops!  Because the above comment was broken into 2 lines by the text editor, we just lost the Pubs table!  The rest of the script will fail, and all our data is gone.
*/ 

SELECT * into #temp_authors
from Authors

DROP TABLE Authors

/********************************************************/
/* Example 2: Using block comments */
USE PUBS
GO

/*
This script will select the contents of the Authors table into a temp table.  Then it drops the Authors table.
*/
/*
Make sure you execute the following statement before you
drop table Authors
*/
/*
Because we used block comments here, the script isn't affected by the fact that the comment was broken up.
*/ 

SELECT * into #temp_authors
from Authors

DROP TABLE Authors

Rate

3.67 (3)

You rated this post out of 5. Change rating

Share

Share

Rate

3.67 (3)

You rated this post out of 5. Change rating