我想在现有表中添加一列,其值取决于另一列STORE。 STORE有两个值,T或D.如果存储值为T,那么我希望添加列中的值为1,否则为零。有什么办法吗?
答案 0 :(得分:3)
虚拟列可以在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
或触发方式,如果你的10g或之前:
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
答案 1 :(得分:2)
Oracle不支持create或alter table命令。
相反,请使用:
ALTER TABLE your_table ADD c INTEGER;
UPDATE your_table SET c = CASE WHEN store = 'T' THEN 1 ELSE 0 END;
答案 2 :(得分:1)
视图可以是一个解决方案:
create view v_your_table as
select your_table.*, case when STORE = 'T' than 0 else 1 end as comp from your_table;