I have a table Items, which has fields Inventory and ItemId (the primary key).
And I have another table Allocations, which has fields Allocation and ItemId, which is a foreign key referencing Items.ItemId.
Thus many Allocations can relate to one Item.
I wonder how I can add a constraint to not allow SUM(Allocation) in the Allocations table for the same ItemId to accede Items.Inventory for that ItemId. I could find only very simple examples, so I am not sure how to approach this problem.
Implementation for Tab Allerman's answer See demo
You can create a CHECK CONSTRAINT on the
Allocations
table that calls a function.Pass the
ItemID
to the function and have the function populate a local variable with theItems.Inventory
for thatItemId
.After that, have the function do a SELECT that gets the
SUM(Allocation)
in theAllocations
table for the sameItemId
, and returnTrue (1)
if the SUM is greater than theInventory
, or elseFalse (0)
.In the CHECK CONSTRAINT, just test whether the Function returns
False
.