MySQL trigger set values for NEW row and update another in the same table

后端 未结 4 1899
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 15:14

I have a table that I keep track of fees for a specific item. These fees can change over time so I have two columns (startDate, endDate) with the current set of fees always

4条回答
  •  心在旅途
    2020-12-01 15:38

    If you have a UNIQUE KEY defined on (procKey,EndDate), then perhaps you can remove the second line of the trigger. Also remove the hardcoded date from the trigger.

    CREATE
    DEFINER=`root`@`%`
    TRIGGER `im`.`splitBeforeIns`
    BEFORE INSERT ON `im`.`split`
    FOR EACH ROW
    BEGIN
        SET NEW.tcPercent = (NEW.tcOfficeFee / NEW.globalFee) * 100 , NEW.proPercent = 100 - NEW.tcPercent;
    END$$
    

    and do an INSERT ON DUPLICATE KEY UPDATE like this:

    INSERT INTO im.split ...
    ON DUPLICATE KEY UPDATE
    endDate = ADDDATE(startDate, -1);
    

    You may also want to define endDate in im.split as follows

    enddate DATE DEFAULT '2050-12-31'
    

提交回复
热议问题