I have some financial values stored as text in a mysql db. the significance of financial is that negative numbers are stored enclosed in paranthesis. is there a way to automatically get the numeric value associated with that text. (like '5' shoudl be retuned as 5 and '(5)' should be returned as -5)
+2
A:
You probably know that enclosing negative values in parentheses is a presentational issue and should not even be in the database to begin with. There are numeric data types for financial values that perfectly cover the negative range and are easy to select/manipulate/aggregate.
Now you are stuck with something horrible along the lines of this:
SELECT
CASE WHEN LEFT(val, 1) = '('
THEN -1 * CAST( REPLACE((val, '(', ''), ')', '') AS DECIMAL(10,4))
ELSE CAST( val AS DECIMAL(10,4) )
END AS num_val
FROM
val_table
Tomalak
2010-04-05 10:00:26
yes i am aware of that. we are getting the values from another source, so it will take some time to fix that. Thanks for your solution. Though we need another replace call in line 3
Midhat
2010-04-05 10:30:49
But i cant seem to use num_val in a where clause. u know nay way to do that? @tomalak
Midhat
2010-04-05 10:31:16
Like this? `WHERE CASE WHEN ... END > 0`
Tomalak
2010-04-05 10:56:52