1

persons is a tinytext field and can contain "4 + 2", "4+2", "4 +2", "5" or "" and so on. I would like to select and int like 6, 6, 6, 5 and 0 from that MySQL 5.6 Table.

Tried this without success:

SELECT CAST(persons AS INT) FROM Table
SELECT CONVERT(INT, persons ) FROM Table
4
  • 3
    With 2K rep you should already know how-to-ask a question on SO. Commented Mar 21, 2019 at 17:01
  • so you want magic to happen? how many operations do you have in those strings? what is the list of operations? -+/* do you want to support braces? Commented Mar 21, 2019 at 17:05
  • No it's only + Operation or just a number or empty. It's an old database that needs to be migrated. Not looking for magic, but you never know if there is something you missed. If there is no solution will do it on server side. Commented Mar 21, 2019 at 17:07
  • Possible duplicate of Summing a comma separated column in MySQL 4 (not 5) Commented Mar 21, 2019 at 17:12

3 Answers 3

3

If + is the only operator and it appears once, then:

select (case when col like '%+%'
             then substring_index(col, '+', 1) + substring_index(replace(col, ' ', ''), '+', -1)
             else col + 0
        end) as added_value
Sign up to request clarification or add additional context in comments.

1 Comment

Works! I knew there must be a way. Thanks!
1

use SUBSTRING_INDEX

 select SUBSTRING_INDEX(col  , "+", 1)+ SUBSTRING_INDEX(col  , "+", -1) as col1
   from cte where col like '%+%'
  union all
  select SUBSTRING_INDEX(col  , "+", 1) from cte where col not like '%+%'

output

  col1
    6
    6
    6
    5

the upper solution will work only for your sample data demo link

3 Comments

I'm afraid this won't work because "persons" can also be "4+2", "4 + 2" or "4+ 2" and so on. I need something like an operation interpretation.
@Mike . . . This will also return 10 instead of 5 for '5'.
@GordonLinoff i just updated answer for only sample data
0

What database are you using? You may need to use something db specific. e.g. in oracle you can do:

select dbms_aw.eval_number ('4+2') from dual

It will return 6.

Generally speaking - using dynamic SQL you can easily achieve this.

2 Comments

It's MySQL Version 5.6
I dont think MySQL allows dynamic SQL inside functions. So simple route of simply letting the SQL engine do it for you will not be available. Based on your needs if you can live with a stored procedure that can certainly call dynamic SQL. Or you can create a function that acytually parses string on +/*- etc. and has a switch statement etc. to compute the result. Not very complex.

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.