Error was due to conflict in the column name with variable name salary
.
It would always be a good practice to use relevant name but not the same name as column name.
And also you need some logical change in updating the total salary in department table.
You are only updating the department's total salary, whenever a new employee is added.
You should also change the same for the department from which this employee is transferred.
Following change to the trigger should be working:
drop trigger if exists `R3`;
DELIMITER $$
CREATE TRIGGER `R3` AFTER UPDATE ON `EMPLOYEE` FOR EACH ROW BEGIN
Declare old_dept_total_salary int;
Declare new_dept_total_salary int;
-- if emp is moved to a new dept, then
-- former dept tot sal affects
select SUM(Salary) into old_dept_total_salary
from Employee
where Employee.deptno = OLD.deptno
group by Employee.deptno;
-- update it
UPDATE DEPARTMENT
SET Total_sal = old_dept_total_salary
WHERE deptno = OLD.deptno;
-- if emp is moved to a new dept, then
-- new dept tot sal too affects
select SUM(Salary) into new_dept_total_salary
from Employee
where Employee.deptno = New.deptno
group by Employee.deptno;
-- update it
UPDATE DEPARTMENT
SET Total_sal = new_dept_total_salary
WHERE deptno = NEW.deptno;
END;
$$
delimiter ;
You also need after insert
and after delete
trigger on employee
to correct the total_sal
field of department
table, whenever a new employee is inserted or an old employee is deleted.
Demo @ MySQL 5.5.32 Fiddle