62

In Microsoft SQL Server 2005, why do the following commands produce integer results?

SELECT cast(151/6 AS DECIMAL(9,2))
SELECT 151/6
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
  • 2
    Possible duplicate of [how to get a float result by dividing two integer values?](http://stackoverflow.com/questions/11719044/how-to-get-a-float-result-by-dividing-two-integer-values) – Ciro Santilli OurBigBook.com Oct 07 '15 at 05:08

8 Answers8

75

In the first you are getting the result of two integers and then casting the result as DECIMAL(9,2). In the second you're just dividing two integers and that's expected.

If you cast one of the integers as a decimal BEFORE you do the division, you'll get a decimal result.

SELECT 151/CAST(6 AS DECIMAL (9,2))
Mike M.
  • 12,343
  • 1
  • 24
  • 28
42

Yes that is standard behavior

do

SELECT 151/6.0

or

SELECT 151/(CONVERT(DECIMAL(9,2),6))

or

SELECT 151/(6 * 1.0)
SQLMenace
  • 132,095
  • 25
  • 206
  • 225
13

Because 151 and 6 are integers and you are doing integer division, even before the cast.

You need to make sure at least one of the arguments is a float type:

SELECT 151.0/6

Or

SELECT 151/6.0
Oded
  • 489,969
  • 99
  • 883
  • 1,009
8

Not a direct answer to your question. Still worth to take a look at Operators in Expressions if you need this in SSRS

/ Divides two numbers and returns a floating-point result.

\ Divides two numbers and returns an integer result.

Mod Returns the integer remainder of a division.

Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418
3

You need to give a placeholder for decimal places as well

Example

SELECT 151.000000/6
OR
SELECT 151/6.000000

Both will produce

25.16666666

Sham Sunder
  • 102
  • 5
1

For the same reason they would in C#, Java and other mainstream languages.

In integer arithmetic, the CAST is after the maths...

Dale K
  • 25,246
  • 15
  • 42
  • 71
gbn
  • 422,506
  • 82
  • 585
  • 676
1

The CAST statement is a bit verbose. You can use the following instead:

DECLARE @TO_FLOAT FLOAT = 1.0;
SELECT (1 * @TO_FLOAT) / 2;

Or use a different multiplier type like DECIMAL if you prefer.

-1

Try this:

SELECT 1.0*cast(151/6 AS DECIMAL(9,2))
SELECT 1.0*151/6
StelioK
  • 1,771
  • 1
  • 11
  • 21