In an SQL statement, I am trying to divide two integers (integer 1 is "abc" in my code below, integer 2 is "xyz" in my code), and get a result as a decimal (def in my code below). The decimal result should have a leading 1 or 0 only, followed by a decimal and 3 numbers after the decimal. However my code keeps returning a straight 0 with no decimals.
SELECT CONVERT(DECIMAL(4,3), abc/xyz) AS def
This code results in "0", when what I want is something like "0.001" or "0.963". I believe that it is still looking at "def" as an integer, and not as a decimal.
I have also tried using CAST on abc and xyz but it returns the same thing. I have also tried the following code:
SELECT CONVERT(DECIMAL(4,3), abc/xyz) AS CONVERT(DECIMAL(4,3)def)
But this gives me an error, saying there is a syntax error near the word "CONVERT".
Convert to decimal before the divide, not after. The convert for answer format.
SELECT
CONVERT( DECIMAL(4,3)
, ( CONVERT(DECIMAL(10,3), abc) / CONVERT(DECIMAL(10,3), xyz) )
) AS def
This should do it. Also add divide by zero check.
SELECT CONVERT(DECIMAL(4,3), abc) / NULLIF(xyz,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