I'm using SQL Server 2005. The datatype is varchar
. I'm trying to convert numbers like
1250000
to
1.25
within the SQL query and drop the trailing zeroes. I have tried a number of things with no success - have run into 'trim is not a function', etc.
Here's what I currently have, in each iteration that I have attempted.
select top 30
var1, var2, var3, var4,
CONVERT(DECIMAL(6,2), (var5 / 1000000)) as 'Number'
from
databasetable
where
var1 = x
select top 30
var1, var2, var3, var4,
cast((var5 / 1000000) as decimal(6,2)) as 'Number'
from
databasetable
where
var1 = x
Both queries above are rounding to the nearest million, i.e. 1250000 becomes 1.00, etc. Any ideas would be much appreciated. Changing decimal to numeric did not help either.
Results:
I can't say for sure without know you're exact platform, but my guess would be its truncating it to an int. I would try converting
var5
and10000000
before doing the math. Something like@marc_s is absolutely right - stop storing numbers as strings!
That said, you're a victim of integer math. Try:
Since you stored numbers as strings, SQL Server may try to perform this calculation with non-numeric data before applying the filter, so you can say:
[Note that this isn't perfect either.]
If this doesn't work then you've got some bad data. If the following does work but yields too many decimal places:
Then try wrapping it with an extra convert:
That all said, why can't you format this number in the presentation layer?
Also, please don't use
'single quotes'
for column aliases ... this syntax is deprecated in some forms, and it incorrectly makes your column alias look like a string (IMHO). Use[square brackets]
or just avoid using keywords as aliases.