为什么这个SQL触发器不起作用?选择总和并更新

时间:2014-04-24 02:45:57

标签: mysql sql triggers

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

薪水是空的,并且因为不可能而抛出错误。

2 个答案:

答案 0 :(得分:0)

如果您收到salaryNULL的错误,则问题不在于此触发器。

这是更新后的触发器,会影响department.tot_salary的值。如果此字段出现问题,则错误会显示为tot_salary,而不是salary

salary会发生employee错误,并且执行此触发器之前会发生。该字段的值可能不是NULL

我的结论是,您尝试使用NULL salary值更新员工记录,并且该字段中不允许该值。

答案 1 :(得分:0)

错误是由于列名称与变量名salary发生冲突 使用相关名称但与列名称不同的名称始终是一个好习惯。

在更新部门表中的总薪水时,您还需要进行一些逻辑更改 只要添加新员工,您只需更新部门的总薪水 您还应该为转移此员工的部门更改相同的内容。

更改触发后应该正常工作:

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 ;

每当插入新员工或旧员工时,您还需要after insert上的after deleteemployee触发器来更正total_sal表的department字段员工被删除。

演示 @ MySQL 5.5.32 Fiddle