Monday, 6 August 2018

SQL Server Arithmatic Operators

SQL server have several  arithmetic operator for computation and  assignment purpose.  Here is the list of operator  add , subtract multiply, divide , modulo , add assign. 
 
  • +     Add     
  • -     Subtract     
  • *     Multiply     
  • /     Divide     
  • %     Modulo
  • +=    Add Assign

 
Here are some in simple  example of operator uses.

1)Add (+)

DECLARE @value1 DECIMAL(10,2),
                @value2 DECIMAL(10,2)

SELECT @value1=5.1
SELECT @value2=1.1

SELECT [Result_of_Sum]=(@value1+@value2)

Output:
Result_of_Sum
6.20


2)Subtract (-)

 
DECLARE @value1 DECIMAL(10,2),
                @value2 DECIMAL(10,2)

SELECT @value1=5.1
SELECT @value2=1.1

SELECT [Result_of_Substract]=(@value1-@value2)

Output:
Result_of_Substract
4.00




3)Multiply (*)

DECLARE @value1 DECIMAL(10,2),
                @value2 DECIMAL(10,2)

SELECT @value1=5.1
SELECT @value2=1.1

SELECT [Result_of_Substract]=(@value1*@value2)


Output:
Result_of_Multiply
4.00

4)/ Divide

DECLARE @value1 DECIMAL(10,2),
                @value2 DECIMAL(10,2)

SELECT @value1=5.1
SELECT @value2=1.1

SELECT [Result_of_Divide]=(@value1/@value2)

Output:
Result_of_Divide
4.6363636363636


5)% Modulo


DECLARE @value1 INT,
               @value2 INT

SELECT @value1=5
SELECT @value2=2

SELECT [Result_of_Modulo]=(@value1%@value2)

Output:
Result_of_Modulo
1

6)+= Add Assign

DECLARE @value1 VARCHAR(500)

SELECT @value1='Hello'

SELECT @value1+=' World'

SELECT @value1


Output:
Result_of_Modulo
Hello World

 

Below is the example of Arithmetic Operators can be used for large and complex calculation.

Example 1

 
SELECT [Result]=((((5+15)*6)/2)*8)

Output:
480

Example 2

DECLARE @l_val1 INT=3
DECLARE @l_val2 INT=2
DECLARE @l_val3 DECIMAL(10,3)=10.2
DECLARE @l_val4 DECIMAL(10,3)=63.5
DECLARE @l_val5 DECIMAL(10,3)=15.8
DECLARE @l_val6 INT=6
DECLARE @l_val7 INT=7

SELECT [Result]=((((@l_val6+@l_val7)*@l_val5)*@l_val4)/@l_val3)+@l_val1+@l_val2


Result:
1283.715686274




No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...