Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server, division returns zero

Tags:

sql

Here is the code I'm using in the example:

 PRINT @set1  PRINT @set2   SET @weight= @set1 / @set2;  PRINT @weight 

Here is the result:

47 638 0 

I would like to know why it's returning 0 instead of 0,073667712

like image 338
Roch Avatar asked Nov 03 '09 10:11

Roch


People also ask

How do you stop Division by zero in SQL?

If you'd like to handle division by zero gracefully, you can use the NULLIF function. NULLIF takes two arguments: the expression of interest, and the value you want to override. If the first argument is equal to the second, then NULLIF returns NULL; otherwise, it returns the first argument.

Is there a divide function in SQL?

The SQL divide ( / ) operator is used to divide one expressions or numbers by another.


2 Answers

Either declare set1 and set2 as floats instead of integers or cast them to floats as part of the calculation:

SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float); 
like image 147
Martin Avatar answered Oct 11 '22 13:10

Martin


When you use only integers in a division, you will get integer division. When you use (at least one) double or float, you will get floating point division (and the answer you want to get).

So you can

  1. declare one or both of the variables as float/double
  2. cast one or both of the variables to float/double.

Do not just cast the result of the integer division to double: the division was already performed as integer division, so the numbers behind the decimal are already lost.

like image 32
Hans Kesting Avatar answered Oct 11 '22 14:10

Hans Kesting