语法检查约束,检查col1 = col2 * col3的值

时间:2013-04-02 13:04:51

标签: sql oracle constraints

关于语法我可能做错了很简单但是在过去的两个小时里我一直在尝试多个语句,在表和列级别定义这个约束时作为CREATE TABLE的一部分并单独尝试然而,使用ALTER TABLE却没有取得任何成功:

Create table tb1 (
tb1_quantity number,
tb1_price number,
tb1_total number constraint tb1_total_CK
CHECK(tb1_total = SUM(tb1_quantity * tb1_price))
);

我一直在尝试的另一种方式是:

Create table tb1 (
tb1_quantity number,
tb1_price number,
tb1_total number constraint tb1_total_CK
CHECK(SUM(tb1_quantity * tb1_price))
)
;

似乎是我正在声明函数的方式,因为我不断得到通常的ORA-00934组功能这里不允许消息。我已经阅读了多种使用触发器和视图的替代方法,但我渴望使用约束来使其工作,我是否使用这种语法的正确行或者只是没有正确写入它?

1 个答案:

答案 0 :(得分:4)

你需要将其定义为一种脱节约束.i.e。:

Create table tb1 (
tb1_quantity number,
tb1_price number,
tb1_total number,
 constraint tb1_total_CK CHECK(tb1_total = tb1_quantity * tb1_price)
);

例如:

SQL> Create table tb1 (
  2  tb1_quantity number,
  3  tb1_price number,
  4  tb1_total number,
  5   constraint tb1_total_CK CHECK(tb1_total = tb1_quantity * tb1_price)
  6  );

Table created.


SQL> insert into tb1 values (1, 1, 1);

1 row created.

SQL> insert into tb1 values (1, 1, 2);
insert into tb1 values (1, 1, 2)
*
ERROR at line 1:
ORA-02290: check constraint (DTD_TRADE.TB1_TOTAL_CK) violated