Caroline
Caroline

Reputation: 3913

Sum two columns with a trigger

I have a table (myTable) with 3 columns [s1, s2, sum]

And I want to add a trigger that automatically updates sum with s1+s2 on each update. Thats my code but it doesn't work. What I'm doing wrong?

Thanks in advance

DROP TRIGGER IF EXISTS `mTrigger`;
DELIMITER //
CREATE TRIGGER `mTrigger` BEFORE UPDATE ON `myTable`
FOR EACH ROW BEGIN

SELECT NEW.s1 + NEW.s2 INTO @sum;

SET @NEW.sum = @sum;

END
//
DELIMITER ;

Upvotes: 0

Views: 3963

Answers (1)

Jon Black
Jon Black

Reputation: 16559

try something like this:

delimiter #

create trigger myTable_before_update_trig before update on myTable
for each row
begin
  set new.sum = new.s1 + new.s2;
end#

delimiter ;

Upvotes: 4

Related Questions