Division in the sqlserver

Asked

Viewed 1,789 times

0

I am using SQL Server 2008, I would like to split 50/100 for example and return me 0.05. However it returns me 0, follows what I tried to do:

inserir a descrição da imagem aqui

2 answers

3


You need to be aware of the data type of the denominator and the divisor. When both are numerical expressions in the domain of integer numbers, the integer division occurs, obtaining the integer quotient. When at least one of them is fractional, the desired division occurs.

-- divisão inteira 
SELECT 50 / 100

-- divisão fracionária
PRINT 50.0 / 100
PRINT 50 / 100.0
PRINT 1.0 * 50 / 100

1

Joseph’s answer is correct, but complementing it can also be like this:

declare @numero decimal(10,3) = 50;

set @numero = @numero / 100;

print @numero

Already declaring the variable as decimal, also works

inserir a descrição da imagem aqui

EDIT: This way it also works:

print convert(decimal(10,2), 50) / 100

First you are converting the number 50 to decimal, and then dividing it

inserir a descrição da imagem aqui

However, I imagine, that in a matter of performance, José’s answer will be better, because of the two forms I showed, one declares variable and arrow it, and the other uses the convert, And in José’s answer, that’s kind of "automatic".. so I think his form is better in performance.

  • 1

    Maike, in everyday life what happens is the use of variables. If the 2 variables (denominator and divisor) are "numerical expressions in the domain of the integers", simply multiply one of them by 1.0 before dividing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.