暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 列默认值为同一表中的另一列

askTom 2016-06-15
278

问题描述

你好,

我们需要在表中添加一个新列,该列需要默认值,例如column1 | | Column2。
由于某种原因,无法更改应用程序代码来处理此新列,因此默认值。

我想到了两种方法可以解决这个问题,如果更新了两列column1或column2中的任何列,则使用触发器来更新新列-因此可以最初更新新列,然后可以启用触发器来处理任何将来的更改。
其他方法是使用虚拟列。

现在看来,新列可能需要直接插入数据或更新,这排除了虚拟列。
在触发器上,网络上充斥着他们有问题的文章,我很难说服对于一个低容量表 (记录数量以及交易数量) 触发器可能不是最糟糕的想法,尽管我理解维护头痛和副作用等。

还有其他方法吗?
另外,为什么Oracle不支持列默认值作为另一列?

谢谢,
普里扬克

专家解答

也许像这样的变化就足够了?


SQL> drop table t purge;

Table dropped.

SQL>
SQL> create table t ( c1 int ,c2 int );

Table created.

SQL> alter table t add c_override int;

Table altered.

SQL> alter table t add c3 int generated always as ( nvl(c_override,c1+c2));

Table altered.

SQL>
SQL> insert into t (c1,c2) values (1,2);

1 row created.

SQL> insert into t (c1,c2,c_override) values (3,4,10);

1 row created.

SQL> select * from t;

        C1         C2 C_OVERRIDE         C3
---------- ---------- ---------- ----------
         1          2                     3
         3          4         10         10

2 rows selected.

--
-- you can hide c_override as well if you like
--

SQL>
SQL> alter table t modify c_override invisible;

Table altered.

SQL> insert into t (c1,c2,c_override) values (5,6,20);

1 row created.

SQL>
SQL> select * from t;

        C1         C2         C3
---------- ---------- ----------
         1          2          3
         3          4         10
         5          6         20

3 rows selected.

--
-- but you still need the app to know its a virtual column not a real one
--
SQL> insert into t (c1,c2,c3) values (1,2,3);
insert into t (c1,c2,c3) values (1,2,3)
                     *
ERROR at line 1:
ORA-54013: INSERT operation disallowed on virtual columns
SQL>
SQL>


「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论