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
薪水是空的,并且因为不可能而抛出错误。
答案 0 :(得分:0)
如果您收到salary
为NULL
的错误,则问题不在于此触发器。
这是更新后的触发器,会影响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 delete
和employee
触发器来更正total_sal
表的department
字段员工被删除。
演示 @ MySQL 5.5.32 Fiddle