Home > SQL Server, T-SQL > SQL SERVER – ABS() – Math Functions @SQLSERVER

SQL SERVER – ABS() – Math Functions @SQLSERVER


ABS() math function gives us a positive value of a given numeric expression. But, We cannot use character data type in the function argument. It may raise an arithmetic overflow error if the numeric value exceeds the data type range.

Examples

select  abs(8)
Output: 8
 
select abs(-7)
Output: 7
 
select abs(-8.8)
Output: 8.8
 
Using bit data in the function
declare @bitvalue as bit
set @bitvalue = 1
select abs(@bitvalue)
Output: 1
 
Alternate method without using ABS() function
declare @intvalue as int
set @intvalue = -89
if @intvalue < 0
set @intvalue = @intvalue * -1
Print  @intvalue
 
Output: 89
 
Example for Arithmetic overflow error
declare @sintvalue as smallint
set @sintvalue = 37000
select abs(@sintvalue)
 
Output:
Msg 220, Level 16, State 1, Line 2
Arithmetic overflow error for data type smallint, value = 37000.
 

I developed these scripts using SQL Server 2012 – 11.0.2218.0. Happy programming!!!

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: