Question

USE `DEPT`;
DELIMITER $$
CREATE DEFINER=`root`@`localhost` TRIGGER `R3` AFTER UPDATE ON `EMPLOYEE` FOR EACH ROW BEGIN
    Declare salary int;
    SET salary = (select SUM(Salary) as salary from Employee where Employee.Dno = New.Dno group by Employee.Dno);
    UPDATE DEPARTMENT set Total_sal = salary where Dno = NEW.Dno;
END

salary is null and is throwing an error because it can't be.

Was it helpful?

Solution

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

OTHER TIPS

If you are getting an error that salary is NULL, then the problem is not with this trigger.

This is an after update trigger that affects the value of department.tot_salary. If there were a problem with this field, then the error would say tot_salary, not salary.

An error on salary would happen for the table employee and occur before this trigger is executed. The value of that field presumably cannot be NULL.

My conclusion is that you are trying to update an employee record with a NULL value for salary and that value is not allowed in the field.

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