SQL Comments

Comments are used by developers to describe SQL statements or logic.

Comments may appear anywhere in the code which is ignored by SQL Server.

Single-line comments start with a double dash: --.

Multi-line comments start with a /* and end with a */

Example

#

This example has a comment describing the SQL.

/* 
 * List all customers from Sweden 
 */
SELECT FirstName, LastName, City, Country 
  FROM Customer
 WHERE Country = 'Sweden'

The comments are ignored and the SQL executes as usual.

Results:  2 records
FirstName LastName City Country
Christina Berglund Luleå Sweden
Marias Larsson Bräcke Sweden

Syntax

Single-line syntax.

-- SQL description

Multi-line syntax.

/* SQL description
   SQL description
   SQL description
   SQL description */

More Examples

SINGLE-LINE COMMENT

A query with a single-line comment.

-- List all suppliers in Brazil

SELECT CompanyName, ContactName, City, Country, Phone
  FROM Supplier
 WHERE Country = 'Brazil'

Again, the comment is ignored and the SQL executes as usual.

Result:  1 record
CompanyName ContactName City Country Phone
Refrescos Americanas LTDA Carlos Diaz Sao Paulo Brazil (11) 555 4640

MULTI-LINE COMMENT

Multi-line comments that describe the query.

/************************************************
 * List the monthly orders for American customers 
 * for the year 2013. Order the list by month.
 ************************************************/

SELECT MONTH(OrderDate) AS Month,
       FirstName, LastName,
       SUM(TotalAmount) AS 'Monthly Sales'
  FROM [Order] O 
  JOIN Customer C ON C.Id = O.CustomerId
 WHERE Country = 'USA' AND YEAR(OrderDate) = 2013
 GROUP BY FirstName, LastName, MONTH(OrderDate)
 ORDER BY MONTH(OrderDate)

This commenting style is referred to as a flower-box.

Result:  830 records
Month FirstName LastName Monthly Total
1 Art Braunschweiger 485.00
1 Paula Wilson 3868.60
1 Yoshi Latimer 102.40
2 Jose Pavarotti 7889.10
2 Rene Phillips 1755.00

INLINE COMMENT

Use inline comments to temporarily hide LastName from the query.
SELECT FirstName /*, LastName */ 
  FROM Customer
 WHERE Country = 'Sweden'

This hiding technique is referred to as commenting out the code.

Result:  2 records
FirstName
Christina
Marias

You may also like



Guides


vsn 3.1