0

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.

1
  • You mean to get the output only numbers and decimal correct? What MySQL version are you using? Might be able to achieve that using REGEXP_REPLACE Commented Dec 10, 2019 at 1:41

1 Answer 1

1

You can use regexp:

select customer_id, val_amt + 0
from my_table
where val_amt regexp '^[0-9]+[.]?[0-9]*';
Sign up to request clarification or add additional context in comments.

2 Comments

Replaced regex with ~ and it worked, but I still do not have val_amt as a float and it still gives me a similar error to the first when I try to cast as a float.
@brightman1309 . . . MySQL supports regexp, not ~: dev.mysql.com/doc/refman/8.0/en/pattern-matching.html (and dbfiddle.uk/…).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.