问题
I have MS Access database file with following tables
Table In
Id | Quantity
------------------------
1 | 8
Table Out
Id | Parent | Quantity
-------------------------
1 | 1 | 2
2 | 1 | 5
Table In
is a parent table and Table Out
is related table.
I need following constraint to be enforced (pseudo formula):
In.Quantity >= Sum(Out.Quantity)
That is: Sum of outgoing quantities cannot be greater than incoming quantity
I am developing a Winforms application. The user will make changes (Insert, Update and delete) to both In
and Out
回答1:
You can use a CHECK
constraint to validate the condition.
ALTER TABLE Out
ADD CONSTRAINT NoNegativeTotal
CHECK(
NOT EXISTS(
SELECT 1
FROM In
INNER JOIN Out ON In.Id = Out.Id
GROUP BY In.Id, In.Quantity
HAVING SUM(Out.Quantity) > In.Quantity
)
)
You might want to add the same constraint to the In
table, since if someone changes the In.Quantity
field to violate the constraint, that'll lock down all editing in the Out
table except edits that make the constraint valid again.
Check constraints need to be executed either in ANSI 92 compatible mode, or using ADO (e.g. using CurrentProject.Connection.Execute
). More details here.
回答2:
Use the BeforeUpdate event of the subform to compare the sum of field Quantity with Me.Parent!Quantity.Value
.
If exceeding, set Cancel = True
and pop a message.
来源:https://stackoverflow.com/questions/57430333/how-to-not-let-sum-of-child-field-not-exceed-parent-field-in-ms-access