简体   繁体   中英

add a column to existing table whose value is dependent on other column

I want to add a column to my existing table whose value is dependent on another column STORE. STORE has two values, T or D. If store value is T, then I want the value in added column to be 1, otherwise zero. IS there any way?

a virtual column can do it in 11g:

SQL> create table yourtab (store varchar2(1));

Table created.

SQL> alter table yourtab add col as (case store when 'T' then 1 else 0 end);

Table altered.

SQL> insert into yourtab (store) values ('T');

1 row created.

SQL> insert into yourtab (store) values ('D');

1 row created.

SQL> select * from yourtab;

S        COL
- ----------
T          1
D          0

or a trigger approach if your on 10g or before:

SQL> create table yourtab (store varchar2(1), col number);

Table created.

SQL> create trigger yourtab_biu
  2  before insert or update on yourtab
  3  for each row
  4  declare
  5  begin
  6    :new.col := case :new.store when 'T' then 1 else 0 end;
  7  end;
  8  /

Trigger created.

SQL> insert into yourtab (store) values ('T');

1 row created.

SQL> insert into yourtab (store) values ('D');

1 row created.

SQL> select * from yourtab;

S        COL
- ----------
T          1
D          0

Oracle does not support this on the create or alter table commands.

Instead, use:

ALTER TABLE your_table ADD c INTEGER;

UPDATE your_table SET c = CASE WHEN store = 'T' THEN 1 ELSE 0 END;

A view could be a solution:

create view v_your_table as
select  your_table.*, case when STORE = 'T' than 0 else 1 end as comp from your_table;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM