Search code examples
oracle-databaseplsqlexpression-evaluation

How to evaluate an expression in one table field into another?


I have a table, inside there is a field called x, the x field contain value of '1+2', '1+3' etc, how to get these value and calculate it and save into another field?


Solution

  • If the case you have mentioned needs to be considered then I will suggest you use the following query:

    select
      xmlquery('3+4'
         returning content
      ).getNumberVal()
    from
    dual;
    

    If More operators are involved except division then the aforementioned query will work but if the division operator is also involved then you must have to replace "/" with " div " keyword. Something like the following:

    select
      xmlquery(
      replace( '20/5', '/', ' div ')
         returning content
      ).getNumberVal()
    from
    dual;
    

    Now, you can use it in your update statement or anywhere else.

    update tab 
    set tab.result_column_name = xmlquery(t.your_expr_column_name
             returning content
          ).getNumberVal()
    
    update tab 
    set tab.result_column_name = xmlquery(
          replace( t.your_expr_column_name, '/', ' div ')
             returning content
          ).getNumberVal()
    

    Demo

    Cheers!!