Compound Operators

I am going to forge ahead with my series of very short articles or tidbits on Transaction SQL Operators. An operator is a symbol specifying an action that is performed on one or more expressions.

I will exploring the Compound Operators today. These operators are a short hand for taking a variable @V, applying some operator O and storing the result as variable @V. A long way to write out adding 2 to variable @V is the expression @V = @V + 2 while the short way is the expression @V += 2.

T-SQL supports the following five compound math operations: ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION, and MODULUS.

The examples below performs a simple calculation using each operator.

The output of each calculation is listed below.

In addition to math, T-SQL supports the following three compound bitwise operations: AND, OR and XOR.

The examples below performs a simple calculation using each operator.

The output of each calculation is listed below.

Please note that I have used both the SELECT and SET statements to perform assignments using compound operators. This means that a variable can be used to get a summation from a query.

For instance, let’s believe the chief financial officer of Adventure Works wanted us to get the hourly run rate for the company. We want to only consider active employees, people who do not have a termination date. The solution below uses a common table expression to find active employees.

The @total variable is used with the addition compound operator to calculate a total hourly cost.

Next time, I will be exploring the Logical Operators.

Related posts

Leave a Comment