2

我想向现有表中添加一列,其值取决于另一列 STORE。STORE 有两个值,T 或 D。如果存储值为 T,那么我希望添加列中的值为 1,否则为零。有什么办法吗?

4

3 回答 3

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
于 2013-03-09T01:24:19.960 回答
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;
于 2013-03-09T01:07:31.300 回答
1

视图可能是一个解决方案:

create view v_your_table as
select  your_table.*, case when STORE = 'T' than 0 else 1 end as comp from your_table;
于 2013-03-09T00:58:38.277 回答