I want to trigger create new rows in b table when a row is inserted to a table.
I have a table staff_leave_application like this:
id | staff | leave type | start date | end date | is half |
---+------------+---------------+------------+----------------+-----------+
1 | John Doe | Casual Leave | 17/01/2013 | 20/01/2013 | 0 |
if a row is inserted in this table, then it will trigger and insert to another table leave
the data to be inserted to leave table:
Split date range start date – end date to day, like :
17/01/2013 - 20/01/2013 will be
17/01/2013
18/01/2013
19/01/2013
20/01/2013
now insert per day to per row of leave table, along with staff_leave_applications column ID, staff, leave type.
I followed @Shaharsh shah’s answer and got this, thanks to 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;
$$
Try this:
DELETE Trigger