Search This Blog

Monday, October 25, 2010

Compound Operators - SQL SERVER 2008/R2

You are aware about arithmetic, bitwise and assignment operators, don’t worry if you are not, see below you will get an idea about them.

Arithmetic Operators: There are 5 arithmetic operators that are Plus (+), Minus (-), Divide (/), Multiply (*) and Modulo (%)

Bitwise Operators: There are three bitwise operators that are Bitwise AND (&), Bitwise OR (|) and Bitwise Exclusive OR (^).

Assignment Operators: There is only one assignment operator Equal to (=)

Example to use them (in Older version):

-- Arithmetic
DECLARE @var INT
SET @var = 1 -- Assignment

SET @var = @var + 2 -- Increment and them assignment
SELECT @var

SET @var = @var - 1 -- decrement and them assignment
SELECT @var

SET @var = @var & 3 -- Bitwise AND and then assignment
SELECT @var

SET @var = @var | 3 -- Bitwise AND and then assignment
SELECT @var


You can see above old method for increment or decrement and then assignment by using Plus (+) and Minus (-) operators. You can use other operators as well in the same way. But this was an old way for of manipulation and then result assignment. We will see enhancement in operator utilization from SQL Server 2008 that is Compound Operators.


Compound Operators:
These operators defined by combining one operator from Arithmetic/Bitwise and 2nd operator from Assignment. It first performs associated operation on left operand with right operand and then saves result to left operand.

These are 8 in numbers.

  1. += (Add EQUALS), you can use it for string concatenation as well.
  2. -= (Minus EQUALS)
  3. *= (Multiply EQUALS)
  4. /= (Divide EQUALS)
  5. %= (Modulo EQUALS)
  6. &= (Bitwise AND EQUALS)
  7. |= (Bitwise OR EQUALS)
  8. ^= (Bitwise Exclusive OR EQUALS)


Example:
Compare this example with above one:


DECLARE @var INT
SET @var = 1 -- Assignment

SET @var += 2 -- Increment and them assignment
SELECT @var

SET @var -= 1 -- Increment and them assignment
SELECT @var


SET @var &= 3 -- Bitwise AND and then assignment
SELECT @var

SET @var |= 3 -- Bitwise AND and then assignment
SELECT @var

No comments: