In Microsoft SQL Server 2005, why do the following commands produce integer results?
SELECT cast(151/6 AS DECIMAL(9,2)) SELECT 151/6
Integer division in SQL takes place when both the dividend and the divisor are integers. Since they are integers, SQL wants to return an integer result to match the number type. In PostgreSQL and SQL Server, it is integer division. In MySQL and Oracle it is regular division (and the result of 1/4 is 0.25 ).
The SQL divide ( / ) operator is used to divide one expressions or numbers by another.
Division of integers means equal grouping or dividing an integer into a specific number of groups. For example, -6 ÷ 2 means dividing -6 into 2 equal parts, which results in -3.
Names and symbols used for integer division include div, /, \, and %.
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))
Yes that is standard behavior
do
SELECT 151/6.0
or
SELECT 151/(CONVERT(DECIMAL(9,2),6))
or
SELECT 151/(6 * 1.0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With