As Annjawn explains in this answer you can use some of the built in functionality of XMLQuery
, specifically .getnumberval()
, to fake the formulae. This will be considerably slower than a CASE statement but it is a lot cleaner.
Assuming the table:
create table tmp_test (
field1 number not null
, field2 varchar2(1) not null
, field3 number not null );
insert all
into tmp_test values (1, '+', 5)
into tmp_test values (1, '*', 5)
into tmp_test values (1, '-', 5)
select * from dual;
Your query would look like this:
SQL> select xmlquery(field1 || field2 || field3 returning content
2 ).getnumberval() as field4
3 from tmp_test;
FIELD4
----------
6
5
-4
SQL Fiddle
I would strongly advise against storing a calculated column in the database though. It will only cause problems as if you update the database your column does not get updated. The correct way to do this is to either have a view, that includes the definition of your calculation and always select from this view or to use a VIRTUAL column as defined in the create table documentation.
You can then either use XMLQuery
or a DETERMINISTIC function, for instance the one provided by APC, to automatically calculate your column.
If your table is created as follows:
create table tmp_test (
field1 number not null
, field2 varchar2(1) not null
, field3 number not null
, field4 number generated always as (
xmlquery(field1 || field2 || field3 returning content
).getnumberval()
) virtual
);
Then a much simpler query will get your result
SQL> select * from tmp_test;
FIELD1 F FIELD3 FIELD4
---------- - ---------- ----------
1 + 5 6
1 * 5 5
1 - 5 -4
SQL Fiddle
The other benefit of this is that your calculations are always done in exactly the same way. They are not implemented differently for each individual piece of code that needs this computed column