Jump Start: Variable Values and Math Operators

Michael Otey explains how to code T-SQL's addition, subtraction, multiplication, division, and modulus math operators.

Michael Otey

January 13, 2008

1 Min Read
Jump Start: Variable Values and Math Operators

Now that you've learned the basics of using the T-SQL SET and SELECT statements to assign values to variables and concatenate variable string values, let's wade farther out and review how to use the basic math operators with T-SQL variables.

T-SQL has built-in operators for all the basic mathematic functions, including addition, subtraction, multiplication, and division. The code below illustrates how to use T-SQL’s mathematic functions with variables.

DECLARE @NUMVAR1 INTDECLARE @NUMVAR2 INTSET @NUMVAR1 = 1SET @NUMVAR2 = 2SELECT @NUMVAR1 + @NUMVAR2SELECT @NUMVAR2 - @NUMVAR1SELECT @NUMVAR2 * @NUMVAR2SELECT @NUMVAR2 / @NUMVAR1SELECT @NUMVAR1 % @NUMVAR2SELECT (@NUMVAR2 * @NUMVAR2) + 3

This sample code first declares two variables, @NUMVAR1 and @NUMVAR2, and assigns them a value of 1 and 2, respectively. The subsequent lines each contain an expression that illustrates the use of (in order) addition, subtraction, multiplication, division, modulus (remainder, indicated by the percent sign--%), and precedence. SQL Server Express uses the same precedence, or order, of evaluating complex mathematical expressions that you learned in grade school, calculating first the portions within parentheses, followed by exponents, multiplication, addition, and subtraction. Running the sample T-SQL code returns the following result for the first through sixth expression, respectively: 3, 1, 4, 2, 1, 7.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like