将ORACLE表字段的默认值设置为公式

时间:2013-02-19 12:49:21

标签: oracle expression default

我有一个像这样的oracle表:

create table tms_transaction_tbl
(
trans_id number primary key,
location_id number,
trans_date date,
resource_id number,
ts_id number,
max_value number,
booked_units number default 0,
remaining number default (select max_value-booked_units),
booked number not null ,
user_id number,
trans_time timestamp
);

你可以看到我试图将剩余的默认值设置为(max_value-booked_units)

remainging number default (select max_value-booked_units),

但是这个错误给了我这个错误

ora-22818:subquery expression not allowed here

2 个答案:

答案 0 :(得分:3)

您不能引用DEFAULT表达式中的其他列

以下是Oracle Documentation

的摘录
  

对默认列值的限制DEFAULT表达式不能   包含对PL / SQL函数或其他列的引用   伪列CURRVAL,NEXTVAL,LEVEL,PRIOR和ROWNUM,或日期   未完全指定的常量。

答案 1 :(得分:2)

您不能将SELECT用作默认值,它必须是常量。

如果你使用的是Oracle 11g,这就是virtual columns的用途。您无法插入或更新它们,但为您提供数据库中预先计算的列。

create table tms_transaction_tbl
 ( trans_id number primary key,
   location_id number,
   trans_date date,
   resource_id number,
   ts_id number,
   max_value number,
   booked_units number default 0,
   remaining number generated always as ( max_value - booked_units ) virtual,
   booked number not null ,
   user_id number,
   trans_time timestamp
   );

语法在CREATE TABLE statement的文档中进一步描述。如果你没有使用11g,你可以通过桌面上的视图实现相同的逻辑。

如果您不想使用视图或虚拟列,那么I can only recommend根本不存储此数据。