我想在create new rows
表中插入行时在b
表中触发a
。
我有一张像这样的表staff_leave_application
:
id | staff | leave type | start date | end date | is half |
---+------------+---------------+------------+----------------+-----------+
1 | John Doe | Casual Leave | 17/01/2013 | 20/01/2013 | 0 |
如果在此表中插入了一行,那么它将触发并插入另一个表leave
要插入leave
表的数据:
将日期范围start date
- end date
拆分为日期,例如:
17/01/2013 - 20/01/2013 will be
17/01/2013
18/01/2013
19/01/2013
20/01/2013
现在每天插入leave
表的每一行,以及staff_leave_application
列ID, staff, leave type
。
我跟着@Shaharsh shah的回答得到了这个,多亏了Sharsh。
DELIMITER $$
USE `mydb`$$
CREATE
/*!50017 DEFINER = 'root'@'localhost' */
TRIGGER `tn_air_staff_leave_application` AFTER INSERT ON `staff_leave_application`
FOR EACH ROW BEGIN
SET @counter := -1;
WHILE (@counter < DATEDIFF(DATE(new.end_date), DATE(new.start_date))) DO
INSERT INTO `leave`(staff_id_staff, leave_type_id_leave_type, staff_leave_application_id_staff_leave_application, leave_date)
VALUES (new.staff_id_staff, new.leave_type_id_leave_type, new.id_staff_leave_application, DATE_ADD(new.start_date, INTERVAL @counter:=@counter + 1 DAY));
END WHILE;
END;
$$
答案 0 :(得分:1)
试试这个:
DELIMITER $$
DROP TRIGGER /*!50032 IF EXISTS */ `tn_air_staff_leave_application`$$
CREATE
/*!50017 DEFINER = 'root'@'localhost' */
TRIGGER `tn_air_staff_leave_application` AFTER INSERT ON `staff_leave_application`
FOR EACH ROW BEGIN
SET @counter := -1;
WHILE (@counter < DATEDIFF(DATE(new.endDate), DATE(new.startDate))) DO
INSERT INTO `leave`(staffId, leaveType, leaveDate)
VALUES (new.id, new.leaveType, DATE_ADD(new.startDate, INTERVAL @counter:=@counter + 1 DAY));
END WHILE;
END;
$$
DELIMITER ;
删除触发器
DELIMITER $$
DROP TRIGGER /*!50032 IF EXISTS */ `tn_adr_staff_leave_application`$$
CREATE
/*!50017 DEFINER = 'root'@'localhost' */
TRIGGER `tn_adr_staff_leave_application` AFTER DELETE ON `staff_leave_application`
FOR EACH ROW BEGIN
DELETE FROM `leave` WHERE staffId = old.id;
END;
$$
DELIMITER ;