Question

I have a table, department , with several bit fields to indicate department types One is Warehouse (when true, indicate the department is warehouse)

And I have another table, ManagersForWarehouses with following structure:

ID autoinc
WarehouseID int (foreign key reference DepartmentID from departments)
ManagerID int (foreign key reference EmployeeID from employees)
StartDate
EndDate

To set new manager for warehouse, I insert in this table with EndDate null, and I have a trigger that sets EndDate for previous record for that warehouse = StartDate for new manager, so a single manager appears for a warehouse at a certain time.

I want to add two check constraints as follows, but not sure how to do this

  1. do not allow to insert into ManagersForWarehouses if WarehouseID is not marked as warehouse
  2. Do not allow to uncheck Warehouse if there are records in ManagersForWarehouses

Thanks

Was it helpful?

Solution

  1. In Departments table, add a unique constraint (DepartmentID, IsWarehouse)
  2. In ManagersForWarehouses table, add column IsWarehouse, and have a CHECK constraint enforce that IsWarehouse='Y'
  3. In ManagersForWarehouses table, add a FK on (WarehouseID , IsWarehouse) referrring to Departments(DepartmentID, IsWarehouse), and with ON UPDATE CASCADE clause.

And you are all set with 100% rock solid integrity, without any loopholes. Only trusted constraints do not have any loopholes. Triggers are less reliable.

OTHER TIPS

You should use a triggers to do this. One on each table. Make sure to account for multiple record inserts, updates or deletes. To do anything else would be putting your data at risk. Data does NOT get into databases only from applications. You cannot afford to enforce this sort of thing from the application unless you want data that is incorrect and useless.

Don't put this kind of constraints on the DB table.
It is better to enforce such a thing using code (business logic).

EDIT: Not related to your question, but you should not use the trigger as well to perform updates to other rows. I don't have solid links to back it up with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top