Using SUM
in a SELECT INTO
statement is valid. But there are some other issues with your trigger:
If you want to DECLARE
a local variable you can't prefix it with an @
-sign like it is required for session variables. The scope of a local variable is only inside the trigger and not globally for the current session as it is for session variables. It is good practice to prefix a local variable (with a v
, i.e.) to distinguish it from unqualified field names in a query, because same names might result in an error or at least unintended behaviour.
Also you need to specify the precision of a DECIMAL
field or variable when you DECLARE
it. The default is DECIMAL(10,0)
. That means the number can be 10 digits long and has no decimal place. If you set it to DECIMAL(8, 2)
, i.e., the number can be 8 digits long, but with 2 of them being decimal places.
DELIMITER //
CREATE TRIGGER bill_log_after_insert AFTER INSERT ON bill_log
FOR EACH ROW
BEGIN
DECLARE v_amount DECIMAL(8, 2);
SELECT SUM(bill_amount)
INTO v_amount
FROM bill_log
WHERE main_fk = NEW.main_fk;
IF v_amount < 0 THEN
UPDATE main SET transaction_type = 'credit' WHERE main_pk = NEW.main_fk;
END IF;
END //
DELIMITER ;
DEMO @ SQL Fiddle