0

i'm trying to create a trigger but there is an error somewhere and since i'm new at this i can't solve it...

So basically i have two tables:

students(stud_num:INT, grade_avg :real)

grading(stud_num:INT, classe:char(5), grade:int)

in students stud_num is the primary key, and in grading it references the table students..

What my professor wants is for me to create a trigger that every time we insert a grade in grading, the grade_avg is updated in students.


This is what i have so far:

DELIMITER %%

CREATE TRIGGER something

AFTER INSERT ON grading

FOR EACH ROW BEGIN

@stud_num=new.stud_num;

UPDATE students

SET grade_avg=(SELECT AVG(grade) FROM grading WHERE stud_num=@stud_num);

END;

%%

Can someone please help me?

2
  • And the error message is.... Commented Nov 27, 2013 at 0:28
  • according to mysql its a syntax error in '@stud_num=new.stud_num;' Commented Nov 28, 2013 at 14:30

1 Answer 1

2

The problem is the way you use the user-defined variable, and you don't actually need it, so you can just skip that by using new.stud_num in place of @stud_num.

You should also restrict your update statement to only update the row for the relevant student, rather than all rows.

DELIMITER %%

CREATE TRIGGER something

AFTER INSERT ON grading

FOR EACH ROW BEGIN

UPDATE students
SET grade_avg=(
  SELECT AVG(grade) 
  FROM grading 
  WHERE stud_num=new.stud_num
)
WHERE stud_num=new.stud_num;

END;

%%

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

Comments

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.