How to compute a column value in oracle 10g?

2019-02-19 07:18发布

问题:

create table ord_tbl
(
ord_id number(10) primary key,
ord_name varchar2(20),
quantity number(20),
cost_per_item number(30),
total_cost number(30)--This colm shud be (quantity*cost_per_item),
ord_date date
)

So when I insert rows then the 'total_cost' should automatically get generated and inserted into a table

回答1:

10g doesn't have this feature. Instead, use a view:

create table ord_tbl
(
ord_id number(10) primary key,
ord_name varchar2(20),
quantity number(20),
cost_per_item number(30),
ord_date date
);

create view vw_ord_tbl as
    select ord_id, ord_name, quantity, cost_perId, (quantity*cost_per_item) as total_cost, ord_date
    from ord_tbl;

The alternative would be to have the column in the table to maintain the value using a trigger -- for both updates and inserts. I would suggest using the view, because maintaining the triggers adds a lot of maintenance overhead.

EDIT (by Jason):

In 11g you can create a virtual column in the table definition.

create table ord_tbl (
    ord_id number(10) primary key,
    ord_name varchar2(20),
    quantity number(20),
    cost_per_item number(30),
    total_cost as (quantity*cost_per_item),
    ord_date date
)


回答2:

Like Gordon Linoff answered, you can create a view. Alternatively you can create a trigger and store the actual value:

create trigger tiua_ord_tbl
on ord_tbl after insert or update
for each row
begin
  :new.total_cost := :new.quantity * :new.cost_per_item;
end;

The advantage of storing the data, is that you can access it faster and index it if you need. The disadvantage is that you store redundant data (it can be calculated at runtime) and it requires more storage space.

I would advise to use the view at first, and only start storing the value in the table if you need this 'cached' version for performance.