对值的约束,oracle数据库

Constraint on values, oracle database

我想在我的 Oracle 数据库中有一个 table,其中 attribute1 的值(值可能会改变)不能大于 [=11 的值(固定) =].

是否可以执行这样的规则? 是否可以使插入后的值无法更改?

禁止 attribute1 大于 attribute2 可以通过 check 约束来完成:

ALTER TABLE mytable 
ADD CONSTRAINT attribute2_greater_check
CHECK (attribute2 >= attribute1)

防止 attribute2 的更新可以通过引发错误的 trigger 来完成:

CREATE OR REPLACE TRIGGER mytable_attribute2_update_tr
BEFORE UPDATE ON mytable
FOR EACH ROW
BEGIN
   IF :NEW.attribute2 != :OLD.attribute2
   THEN
       RAISE_APPLICATION_ERROR(-20101, 'attribute2 cannot be updated');
   END IF;
END;
/

一种方法是在创建 table 时使用适当的 CONSTRAINT:

CREATE TABLE table_name
(
  column1 integer,
  column2 integer not null,

  CONSTRAINT constraint_name CHECK (column1 <= column2)
);

INSERT INTO table_name VALUES(1,1); //ok
INSERT INTO table_name VALUES(2,1); //gives an error

此类约束可以使用手头 table 中的任何字段,但不能通过子选择访问其他 table。

编辑:我刚刚意识到你还问了另一个问题……@Mureinik 已经回答了。