简体   繁体   中英

Mysql said: #1422 - Explicit or implicit commit is not allowed in stored function or trigger

In the code below I'm trying to create a trigger which inserts 'incidentimg' table id along with an image path if the user of the web application did not upload a image with the form belonging to 'incidentreport' table, however, I'm only getting the error " MySQL said: #1422 - Explicit or implicit commit is not allowed in stored function or trigger "

DROP TRIGGER IF EXISTS `insertImage`;
CREATE TRIGGER `insertImage` AFTER INSERT ON `incidentreport` 
FOR EACH ROW 
BEGIN 
    IF(SELECT incidentimg.incidentImgId FROM incidentimg 
       LEFT JOIN incidentreport ON incidentimg.imgs_incidentReportId = incidentreport.incidentReportId 
       WHERE incidentimg.incidentImgId IS NULL) 
       THEN INSERT INTO incidentimg(incidentImgId, imgUrl)values(NEW.incidentReportId, 'images/no-image.png'); 
    END IF; 
END
;

Here are the tables being used 在此处输入图片说明

Can someone assist me on how to correct this problem

I finally got the code to work. Now the code will check whether 'incidentimg' table has all the 'incidentReportId' that the 'incidentreport' table has, and if it doesn't then the last inserted id from the 'incidentreport' table along with a default image path will be inserted into 'incidentimg' table AFTER INSERT.

CREATE TRIGGER insertImage AFTER INSERT ON incidentreport
FOR EACH ROW    
BEGIN
    IF(SELECT incidentreport.incidentReportId 
        FROM incidentreport
        LEFT JOIN incidentimg ON incidentreport.incidentReportId = incidentimg.imgs_incidentReportId
        WHERE incidentimg.imgs_incidentReportId IS NULL)
        THEN INSERT INTO incidentimg(imgs_incidentReportId, imgUrl) VALUES(NEW.incidentReportId, 'images/no-image.png');
    END IF;
END

I am not much sure but I am guessing that probably it's because of the IF .. THEN conditional INSERT . Try modifying your INSERT statement with an EXISTS like

DROP TRIGGER IF EXISTS `insertImage`;
CREATE TRIGGER `insertImage` AFTER INSERT ON `incidentreport` 
FOR EACH ROW 
BEGIN 
INSERT INTO incidentimg(incidentImgId, imgUrl)
SELECT NEW.incidentReportId, 'images/no-image.png'
FROM DUAL WHERE EXISTS (
SELECT 1 FROM incidentimg 
       LEFT JOIN incidentreport 
ON incidentimg.imgs_incidentReportId = incidentreport.incidentReportId 
WHERE incidentimg.incidentImgId IS NULL
)  
END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM