0

When my users_reputation points table gets updated (insert), I want to take a new count (SUM) of this user's points and update a total_rep column in the users table.

This is what I came up with but keep getting syntax errors. I would greatly appreciate if somebody could point out my mistakes.

CREATE TRIGGER after_insert_rep_points AFTER INSERT ON users_reputation
FOR EACH ROW
BEGIN
DECLARE new_total INT(10);
SELECT SUM(rep_points) INTO new_total FROM users_reputation
WHERE user_id = NEW.user_id;
UPDATE users SET rep_total = new_total WHERE user_id = NEW.user_id;
END

These are my table examples for reference:

USERS:

  user_id    |  first_name    |  total_rep
-------------+----------------+--------------
  10001      |  Jim           |  17
  10002      |  Bob           |  5

USERS_REPUTATION:

  user_id  |  rep_task                     |  rep_points  |  rep_date
-----------+-------------------------------+--------------+-----------------------
  10001    |  Commented on article         |  5           |  2012-11-12 08:40:32
  10001    |  Read an article              |  2           |  2012-06-12 12:32:01
  10001    |  Shared an article            |  10          |  2012-06-04 17:39:44
  10001    |  Read an article              |  2           |  2012-05-19 01:04:11
  10002    |  Commented on article         |  5           |  2012-06-17 09:34:21

1 Answer 1

2

You need to add a delimiter change at the beginning.

delimiter |

CREATE TRIGGER after_insert_rep_points AFTER INSERT ON users_reputation
...
END

|
delimiter ;

The delimiter signals the DB engine the end of your statement. Normally it is ;. But that would end the stored procedure at the first ;. And its definition would be incomplete.

You can change the delimiter and add it to the end of your procedure. After that change the delimiter back to ;

Sign up to request clarification or add additional context in comments.

2 Comments

And my shared hosting account doesn't support 'Super User' MySQL privileges! So that was a waste of an hour! Thanks anyway :)
Jeez, I hate it when I spend hours on an issue, start to post a question, then the final "Questions that may already have your answer" points me to an answer. Like here. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.