甲骨文限制实体中的行数

时间:2016-11-05 05:45:10

标签: oracle

我想限制实体中的行数。 例如,我创建了一个表系列(id,name),我希望在族表中不能插入超过5行。 任何有此建议的人都将不胜感激。

1 个答案:

答案 0 :(得分:2)

对于聚合或来自多个表的数据的约束,可以创建帮助器MATERIALIZED VIEW

HUSQVIK@HQ_PDB_TCP> CREATE TABLE family (id NUMBER PRIMARY KEY, name VARCHAR2(255));

Table created.

HUSQVIK@HQ_PDB_TCP> CREATE MATERIALIZED VIEW LOG ON family WITH ROWID INCLUDING NEW VALUES;

Materialized view log created.

CREATE MATERIALIZED VIEW family_count
REFRESH FAST ON COMMIT
AS SELECT count(*) family_count FROM family;

Materialized view created.

HUSQVIK@HQ_PDB_TCP> ALTER MATERIALIZED VIEW family_count ADD CONSTRAINT max_family_count CHECK (family_count <= 5);

Materialized view altered.

HUSQVIK@HQ_PDB_TCP> INSERT INTO family (id, name) values (1, 'Family 1');

1 row created.

HUSQVIK@HQ_PDB_TCP> INSERT INTO family (id, name) values (2, 'Family 2');

1 row created.

HUSQVIK@HQ_PDB_TCP> INSERT INTO family (id, name) values (3, 'Family 3');

1 row created.

HUSQVIK@HQ_PDB_TCP> INSERT INTO family (id, name) values (4, 'Family 4');

1 row created.

HUSQVIK@HQ_PDB_TCP> INSERT INTO family (id, name) values (5, 'Family 5');

1 row created.

HUSQVIK@HQ_PDB_TCP> COMMIT;

Commit complete.

HUSQVIK@HQ_PDB_TCP> INSERT INTO family (id, name) values (6, 'Family 6');

1 row created.

HUSQVIK@HQ_PDB_TCP> COMMIT;
COMMIT
*
ERROR at line 1:
ORA-12008: error in materialized view refresh path
ORA-02290: check constraint (HUSQVIK.MAX_FAMILY_COUNT) violated