0

Why do I get 3 when I execute this T-SQL script:

SELECT 10/3;

I have tried :

SELECT CAST((10/3) AS decimal(5,2));

But now I get 3.00 - still not what I expected

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
molekula
  • 9
  • 2

2 Answers2

4

If you are using two integers in a division it will do integer division. You need to cast at least one of the integers to float or decimal before the division to get what you are looking for.

Dason
  • 60,663
  • 9
  • 131
  • 148
4

{int}/{int}={int}. SQL Server, or any good language fior that matter, won't implicitly change the data type of a expressions results when only 1 data type is involved (in this case int). Thus 10/3 = 3 is correct.

As for the latter, you still have {int}/{int}={int}, but you then convert the result to a decimal. 3 as a decimal is 3.00 so that too is correct.

You need to convert one of values before you divide; changing the data type of either the dividend or the divisor works. For example:

SELECT (10 * 1.) / 3,
       10 / CONVERT(decimal(2,0),3);
Thom A
  • 88,727
  • 11
  • 45
  • 75