Bob Stearns wrote:
For a given invoice/receipt I have the line items sold and possibly
multiple receipt lines: cash, check and credit card(s). The business
rule I wish to enforce is that the sum of the amounts of line items is
equal to the sum of the amounts of receipts. Where and how is such a
rule coded? CHECK(invoice_status<>'PAID' || select sum=select sum)? A
trigger on updating invoice which does a similar thing? Best practice
references would be welcome as well as anything you might have come up with.
This can be done with an ON INSERT TRIGGER, that checks new.amount
before allowing the change, and RAISEs an EXCEPTION if it is not. It
can also be done via a third TABLE, in which the sums of both are kept
(also with ON INSERT TRIGGERs) and a CONSTRAINT can be used there.
But, i'd like to add that this does not sound like a business rule.
This sounds like a check to be done in the application to review what
happened after a full transaction. Because whether the receipts add up
to the correct amount or not has nothing to do with if it was actually
received. Thus, it is a not a data related rule, rather, it is an
interface rule, which is best put in the application. Or, perhaps, a
PROCEDURE could be used to do the actual INSERT and just bar TABLE
access.
B.