tags:

views:

46

answers:

3

Is it possible to create a table with a column that combines two column values? something like this:

create table test1 ( number1 decimal(6,2), number2 decimal(6,2), total decimal(6,2) DEFAULT (number1+number2) );

A: 

You need to use computed columns.

Danil
+4  A: 

Yes, in 11G. It is called a "virtual" column. The syntax is:

create table test1
 ( number1 number(6,2),
   number2 number(6,2),
   total number(6,2) generated always as (number1+number2) );

(There isn't a DECIMAL datatype in Oracle AFAIK, so I used NUMBER instead.)

See also: documentation

NB The "generated always" keywords are optional.

The types of expression allowed after "as" are described here.

Tony Andrews
Just an aside - DECIMAL works fine in Oracle, but I believe it's translated to NUMBER internally.
Bob Jarvis
You're right, I wasn't aware of that.
Tony Andrews
thanks, this works perfectly!
Jay
Is it also possible to use the "generated always as" to use an inner select?
Jay
like generat always as (select sum(*) from table) or something like that?
Jay
No, you would need to calculate via a trigger in that scenario - see Bob Jarvis's answer.
Tony Andrews
A: 

You can do this using a trigger:

create table test1
  (number1 decimal(6,2),
   number2 decimal(6,2),
   total decimal(6,2));

CREATE TRIGGER test1_bi
  BEFORE INSERT ON test1
  FOR EACH ROW
BEGIN
  IF :new.total is NULL THEN
    :NEW.TOTAL := :new.number1 + :new.number2;
  END IF;
END test1_bi;

INSERT INTO test1(number1, number2) VALUES(1, 2);

SELECT * FROM test1;

After the SELECT you'll find that TOTAL has a value of 3, as expected.

Share and enjoy.

Bob Jarvis