Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

"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 
asselect Project_manager_employee_id
        , count(*) as no_of_projects
from project
groupby Project_manager_employee_id
/

The magic is:

altertable project_manager
   addconstraint 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

Solution 2:

I would do the following:

  1. Create new column projects_taken (tinyint) (1) (takes values of 1,2 or 3) with default value of 0.
  2. When manager takes project, the field will increment by 1
  3. Do simple checks (through the UI) to see if the field projects_taken is equal or smaller than 3.

Solution 3:

I would do the following:

  1. Create one SP for both operation insert/update.
  2. Check with IF not exists Project_manager_employee_id(FK) count < 3 then only proceed for insert/update. otherwise send Throw error.

Post a Comment for "Allow Only 3 Rows To Be Added To A Table For A Specific Value"