Friday, December 16, 2011

Using Compound Assignment Operators


With SQL Server 2008 you now can use compound assignment operators for setting variables. A compound assignment operator it the combination of an operator and an equal sign (i.e. +=).   For example say you want to increment the variable @i by by 1.  In SQL Server 2005, or earlier you would this logic by doing this:

SET @i = @i + 1;

Now in SQL Server 2008 you can perform this logic with fewer key strokes, like so:

SET @i += 1;

This <operater>= can be perform with all the different arithmetic operators. 


DECLARE @I INT;
SET @I = 1;
SET @I += 2;
-- Add 2 to @I
SELECT @I;
-- Subtract 1 from @I
SET @I -= 1;
SELECT @I;
-- Multiple @I by 15
SET @I *= 15;
SELECT @I;
-- Divide by @I by 10
SET @I /= 10;
SELECT @I;
-- Return Remainder when dividing @I by 2
SET @I %= 2;
SELECT @I;
-- XOR Operator
SET @I ^=3;
SELECT @I;
-- AND operator
SET @I &= 6;
SELECT @I; 
-- OR operator
SET @I |= 4;
SELECT @I;

No comments:

Post a Comment