-1

行がテーブルに挿入されたときにテーブルでトリガーcreate new rowsし たい。ba

私はこのようなテーブルを持っています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

ここで、 s列 leaveとともに、テーブルの行ごとに1日ごとに挿入します。staff_leave_applicationID, staff, leave type

私は@Shaharshshahの答えに従い、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;
$$
4

1 に答える 1

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 ;
于 2013-01-16T09:38:53.617 に答える