396
Part IV: Programming with T-SQL
Incrementing Variables
T-SQL has the increment variable feature, which saves a few keystrokes when coding and
certainly looks cleaner and more modern.The basic idea is that an operation and equals sign will perform that function on the vari-
able. For example, the codeSET @x += 5;is the logical equivalent ofSET @x = @x + 5The next short script walks through addition, subtraction, and multiplication using the
new variable increment feature:DECLARE @x INT = 1SET @x += 5
SELECT @xSET @x -=3
SELECT @xSET @x *= 2
SELECT @xResult (of whole batch):-----------
6-----------
3-----------
6Conditional Select
Because the SELECT statement includes a WHERE clause, the following syntax works well,
although those not familiar with it may be confused:SELECT @Variable = expression WHERE BooleanExpression;The WHERE clause functions as a conditional IF statement. If the boolean expression is
true, then the SELECT takes place. If not, the SELECT is performed, but the @Variable is
not altered in any way because the SELECT command has no effect.c16.indd 396c16.indd 396 7/30/2012 5:38:06 PM7/30/2012 5:38:06 PM
http://www.it-ebooks.info