393
Chapter 16: Programming with T-SQL
16
Bracketed comments begin with /* and conclude with */. These comments are useful for
commenting out a block of lines such as a code header or large test query:
/*
Product Table INSERT
Version 1.0
May 15, 2012
*/
A benefi t of bracketed comments is that a large multiline query within the comments may
be selected and executed without altering the comments.
Working with Variables
Every language requires variables to temporarily store values in memory. T-SQL variables
are created with the DECLARE command. The DECLARE command is followed by the vari-
able name and data type. The available data types are similar to those used to create
tables, with the addition of the table and cursor. The deprecated text, ntext, and
image data types are only available for table columns, and not for variables. Multiple
comma-separated variables can be declared with a single DECLARE command.
Variable Default and Scope
The scope, or application and duration, of the variable extends only to the current batch.
Newly declared variables default to NULL and must be initialized if you want them to have
a value in an expression. Remember that NULL added to a value yields NULL.
The following script creates two test variables and demonstrates their initial value and
scope. The entire script is a single execution, even though it’s technically two batches
(separated by a GO), so the results of the three SELECT statements appear at the conclusion
of the script:
DECLARE @Test INT ,
@TestTwo NVARCHAR(25);
SELECT @Test, @TestTwo;
SET @Test = 1;
SET @TestTwo = 'a value';
SELECT @Test, @TestTwo ;
GO
SELECT @Test AS BatchTwo, @TestTwo;
c16.indd 393c16.indd 393 7/30/2012 5:38:05 PM7/30/2012 5:38:05 PM
http://www.it-ebooks.info