I am going to continue the 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 Assignment Operator today. This equality symbol = in mathematics.
There are two ways in which the assignment operator can be used: alias – associating a column heading with a expression or storage – placing the results of a expression into a variable.
The TSQL example below compares the assignment operator against old and new ANSI standards for aliasing.
1 2 3 4 5 6 7 8 9 10 11 12 |
-- -- Assignment operator - usage 1 -- -- Assignment same as alias select x = 2 * 3; -- Old school alias select 2 * 3 y; -- New school alias select 2 * 3 as z; |
The output of each calculation is listed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
output: x ----------- 6 y ----------- 6 z ----------- 6 |
The TSQL example below is a good example of using the assignment operator to store the results of a expression into a variable. It creates a temporary table, declares a local variable and sums up the numbers in the temporary table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
-- -- Assignment operator - usage 2 -- -- Create sample table drop table #numbers; create table #numbers (n int); -- Add data 2 table insert into #numbers values (1), (2), (3), (4), (5); select * from #numbers; -- Allocate local variable declare @t int = 0; -- Sum column in table select @t = @t + n from #numbers; select @t as total; |
The output of the summation is listed below.
1 2 3 4 5 |
output: total ----------- 15 |
Next time, I will be exploring the Bitwise Operators.