Tuesday, July 25, 2006

Integer Math In SQL Server

If you divide with 2 integers in SQL Server the result will be also an integer( 3/2 =1, 5/2 =2)
If you need the fractions then you need to convert/cast to decimal/numeric or multiply one of the integers by 1.0

Let's test this out

DECLARE @Value1 INT
DECLARE @Value2 INT

SELECT @Value1 =3,@Value2 =2

--here is where we get 1 instead of 1.5
SELECT @Value1/@Value2

--after using convert the result is correct
SELECT @Value1/CONVERT(DECIMAL(3,2),@Value2)

--after using cast the result is correct
SELECT @Value1/CAST(@Value2 AS DECIMAL(3,2))

--after multiplying with 1.0 the result is correct
SELECT @Value1/(@Value2*1.0)


--this won't work since the multiplication is done after we have the result
SELECT @Value1/@Value2*1.0

No comments: