Question

I want to take the sum of every bill amount of the same foreign key. If the sum is less than zero, I want to update an enum field in the fk table. I haven't been able to find anything about using sum() in a SELECT INTO but it would be great if it worked.

CREATE TRIGGER `bill_log_after_insert` AFTER INSERT ON `bill_log` 
FOR EACH ROW 
  DECLARE @amount DECIMAL;
  SELECT 
    SUM(`bill_amount`) 
  INTO 
    @amount 
  FROM
    `bill_log`
  WHERE 
    `main_fk` = NEW.`main_fk`; 
  IF @amount < 0 THEN 
    UPDATE `main` SET `transaction_type` = 'credit' WHERE `main_pk` = NEW.`main_fk`; 
  END IF;
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top