views:

167

answers:

3

Hi,

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

A: 

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.

shahkalpesh
no, it must be in the database or data integrity will be lost! This is exaclty the kind of thing must be enforced at the database level.
HLGEM
@HLGem: Care to explain why? and how this specific type of constraint can be enforced?
shahkalpesh
A: 

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.

HLGEM
@HLGEM: How does the data get into database? You are right, if there is data movement into DB from sources other than application.
shahkalpesh
Yes, I know I shoud use triggers, but not sure how those triggers should looks like. I'm more an application developer and less a DB guy, so don't know Tsql that good. But I could handle it with some directions. Thanks
bzamfir
@HLGEM: why use triggers when it is so easy to implement with constraints?
AlexKuznetsov
+1  A: 
  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.

AlexKuznetsov
Thank you for your idea.
bzamfir