gpt4 book ai didi

sql - 向现有表添加一列,其值依赖于其他列

转载 作者:行者123 更新时间:2023-12-02 08:42:32 27 4
gpt4 key购买 nike

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

最佳答案

虚拟列可以在 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

关于sql - 向现有表添加一列,其值依赖于其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15305857/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com