First page Back Continue Last page Image

Example: A Trigger with a query and error checking

DELIMITER //

 

CREATE TRIGGER invoices_before_update

BEFORE UPDATE ON invoices

FOR EACH ROW

BEGIN

DECLARE sum_line_item_amount DECIMAL(9,2);

SELECT SUM(line_item_amount)

INTO sum_line_item_amount

FROM invoice_line_items

WHERE invoice_id = NEW.invoice_id;

IF sum_line_item_amount != NEW.invoice_total THEN

SIGNAL SQLSTATE 'HY000'

SET MESSAGE_TEXT =

'Line item total must match invoice total.';

END IF;

END//

OLD vs NEW

You are working on an UPDATE which means the target object had values before you started (OLD) and different values after you finish (NEW)

You can access both sets of values using the OLD and NEW keywords

UPDATE invoices

SET invoice_total = 600

WHERE invoice_id = 100

An example of a statement that would activate the trigger