仅允许将 3 行添加到特定值的表中

2022-01-09 00:00:00 sql insert oracle sql-insert

我手头有一个问题,我需要将分配给经理的项目数量限制为 3 个.表格是:

I have a question in hand where i need to restrict the number of projects assigned to a manager to only 3. The tables are:

Manager:
Manager_employee_id(PK)
Manager_Bonus

Project:
project_number(PK)
Project_cost
Project_manager_employee_id(FK)

谁能建议采取什么方法来实现这一点?

Can anyone suggest what approach to take to implement this?

推荐答案

如何实现对 0,3 的限制?"

"How do I implement the restrict to 0,3?"

这需要一个断言,它在 SQL 标准中定义,但在 Oracle 中没有实现.(虽然有引入它们的举措).

This requires an assertion, which is defined in the SQL standard but not implemented in Oracle. (Although there are moves to have them introduced).

您可以做的是使用物化视图来透明地执行它.

What you can do is use a materialized view to enforce it transparently.

create materialized view project_manager
refresh on commit 
as 
select Project_manager_employee_id
        , count(*) as no_of_projects
from project
group by Project_manager_employee_id
/

魔法是:

alter table project_manager
   add constraint project_manager_limit_ck check 
       ( no_of_projects <= 3 )
/

如果经理的项目计数超过三个,此检查约束将阻止刷新物化视图,该失败将导致触发插入或更新失败.诚然,它并不优雅.

This check constraint will prevent the materialized view being refreshed if the count of projects for a manager exceeds three, which failure will cause the triggering insert or update to fail. Admittedly it's not elegant.

因为 mview 在提交时刷新(即事务性),您需要在 project 表上构建日志:

Because the mview is refreshed on commit (i.e. transactionally) you will need to build a log on project table:

create materialized view log on project

相关文章