views:

34

answers:

1

Using MySQL 5.0.27

This query: SELECT CAST('543.21' AS DECIMAL(100,2))

returns 543.21

So does this one: SELECT CAST('543.21' AS DECIMAL(2,2))

In fact, I am having trouble figuring out what effect the parameter has. I am using it to aggregate numeric values in a varchar column (for legacy reasons!!) and round off to 2 decimal places.

Should I just pick a high number?

A: 

It describes how many total digits a field (or variable) will be able to store. DECIMAL(100,2) - 100 total digits, 98 before, 2 after a decimal separator DECIMAL(2,2) 2 total digits, 0 before, 2 after a decimal separator

Explained here: http://dev.mysql.com/doc/refman/5.1/en/numeric-types.html

[added]

For rounding just use ROUND() function.

Mchl
Then why doesn't `SELECT CAST('543.21' AS DECIMAL(2,2))` return `.21` ?
James Curran
It does return 0.99 for me. Which MySQL version you have?It seems there were some changes in this area between 5.0 and 5.1http://dev.mysql.com/doc/refman/5.1/en/precision-math-decimal-changes.html
Mchl
You'd think it should throw an error like SQL Server does (Arithmetic overflow). (Just my $0.02.)
Cory Larson
@Cory Larson: Depending on SQL mode setting it might actually do (did not test).
Mchl
Thanks this is very helpful.I was in fact trying to effectively cast and round at the same time using CAST(val AS DECIMAL) but it seems the ROUND() function does an implicit type conversion.
Lars
A change was committed to the MySQL 5.0 tree that handles overflows by returning the highest number that still fits within the bounds of the decimal scale and precision specified. The 0.99 you see is because of that functionality, but it should still show you a warning "Out of range value adjusted for column '...' at row x."
Cory Larson
It does show the warning. I just usually don't pay much attention to them ;)
Mchl