Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

sql - Allow only 3 rows to be added to a table for a specific value

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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
/

The magic is:

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...