392
Part IV: Programming with T-SQL
T-SQL Formatting
Throughout this book, T-SQL code has been formatted for readability; this section specifi es
the details of formatting T-SQL code.
Statement Termination
The ANSI SQL standard is to place a semicolon (;) at the end of each command to termi-
nate it. When programming T-SQL, the semicolon is optional. Most other database products
(including Access) do require semicolons.
There are a few rules about using the semicolon:
■ (^) Don’t place one after an END TRY.
■ Don’t place one after an IF or WHILE condition.
■ (^) You must place one before any CTE if it is not the fi rst statement in the batch.
■ Don’t place one after BEGIN.
■ (^) A statement terminator is required following a MERGE command.
As of SQL Server 2012, not terminating a SQL statement with a semicolon has been deprecated. This means that in a
future version of SQL Server, all T-SQL will require a semicolon terminator.
Line Continuation
T-SQL commands, by their nature, tend to be long. One author has written production
queries with multiple joins and subqueries that were a few pages long. It’s nice that T-SQL
ignores spaces and end-of-line returns. This smart feature means that long lines can be
continued without a special line-continuation character, which makes T-SQL code signifi -
cantly more readable.
Comments
T-SQL accepts both simple comments and bracketed comments within the same batch. The
simple comment begins with two hyphens and concludes with an end-of-line:
-- This is a simple comment
Simple comments may be embedded within a single SQL command:
SELECT Name, ProductID -- selects the columns
FROM Production.Product -- the source table
WHERE Name LIKE 'Hex%'; -- the row restriction
Management Studio’s Query Editor can apply or remove simple comments to all
selected lines. Select either Edit ➪ Advanced ➪ Comment Selection (Ctrl+K, Ctrl+C) or
Edit ➪ Advanced ➪ Uncomment Selection (Ctrl+K, Ctrl+U), respectively.
c16.indd 392c16.indd 392 7/30/2012 5:38:05 PM7/30/2012 5:38:05 PM
http://www.it-ebooks.info