brightman1309
brightman1309

Reputation: 33

MySQL type conversion while ignoring nonnumeric characters

How do I convert from varchar(500) to float in MySQL while ignoring non-numeric characters? My code currently looks like this

select distinct(customer_id), cast(val_amt as float) from(
select prsn_real_gid, vital_nam, vital_performed_date,
case when val_amt ~'^[0-9]+' then val_amt else null end as val_amt from my_table);

but I get the following error message

[Amazon](500310) Invalid operation: Invalid digit, Value 'X', Pos 2, Type: Double 
Details: 
 -----------------------------------------------
  error:  Invalid digit, Value 'X', Pos 2, Type: Double 
  code:      1207
  context:   1.XYXY04
  query:     4147
  location:  :0
  process:   query0_118_4147 [pid=0]
  -----------------------------------------------;
1 statement failed.

My data for example looks like this:

customer_id  |  val_amt
111  | 23.45
112  | 21
113  | x
114  | /
115  | 
116  | 23/24

As you can see I have decimals, integers, letters, symbols and nulls. I want to ignore everything that's not a decimal or integer.

Upvotes: 0

Views: 38

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269633

You can use regexp:

select customer_id, val_amt + 0
from my_table
where val_amt regexp '^[0-9]+[.]?[0-9]*';

Upvotes: 1

Related Questions