如果在获取表中没有数据,则在插入火灾错误之前触发。

时间:2017-02-06 13:51:08

标签: mysql triggers

CREATE TRIGGER `staff_auto_salary` BEFORE INSERT ON `staff_attendance`
FOR EACH ROW BEGIN 
IF NEW.att_present LIKE  'P'
THEN 
SET NEW.wages = (SELECT staff_emp_salary FROM staff_salary WHERE staff_emp_id = NEW.att_staff_id ) / (SELECT DAY( LAST_DAY( NOW( ) ) ) );
ELSEIF NEW.att_present LIKE  'HALF' THEN SET NEW.wages = ( SELECT staff_emp_salary FROM staff_salary WHERE staff_emp_id = NEW.att_staff_id ) / ( SELECT DAY( LAST_DAY( NOW( ) ) ) ) /2;
END IF ;
END

以上是我的触发器代码,此触发器根据员工薪水增加了工资,这些工资在staff_emp_salary表中。当插入staff_attendance表时触发器将触发,如果工资不在表中,则从staff_salary获取工资然后它将触发错误,所以我想如果在staff_emp_salary表中没有雇员的工资然后插入0。

1 个答案:

答案 0 :(得分:0)

我喜欢以下解决方案。

DROP TRIGGER IF EXISTS `staff_auto_salary`;
DELIMITER //
CREATE TRIGGER `staff_auto_salary` BEFORE INSERT ON `staff_attendance`
FOR EACH ROW BEGIN 
IF NEW.att_present LIKE  'P'
THEN 
SET NEW.wages = (SELECT IF(count(`staff_emp_salary`)!=0,`staff_emp_salary`,'0') as `staff_emp_salary` FROM staff_salary WHERE staff_emp_id = NEW.att_staff_id ) / (SELECT DAY( LAST_DAY( NOW( ) ) ) );
ELSEIF NEW.att_present LIKE  'HALF' THEN SET NEW.wages = ( SELECT IF(count(`staff_emp_salary`)!=0,`staff_emp_salary`,'0') as `staff_emp_salary` FROM staff_salary WHERE staff_emp_id = NEW.att_staff_id ) / ( SELECT DAY( LAST_DAY( NOW( ) ) ) ) /2;
END IF ;
END //
DELIMITER ;