Mysql – Dynamically records not getting to cursor in trigger

cursorsMySQLtrigger

I am using cursor in trigger in MySQL. I want to get records of recently added id. I am using this:

CREATE DEFINER=`root`@`localhost` TRIGGER `calculate_property_ratings` AFTER INSERT ON `node` FOR EACH ROW BEGIN
DECLARE property_id integer;
DECLARE ratings integer;
DECLARE cur CURSOR FOR SELECT field_rating_rating, field_property_detail_target_id from field_data_field_rating as fr JOIN field_data_field_property_review as pr on pr.field_property_review_target_id = fr.entity_id JOIN field_data_field_property_detail as pd on pd.entity_id = pr.entity_id WHERE pr.field_property_review_target_id = NEW.nid;

DECLARE EXIT HANDLER FOR NOT FOUND BEGIN END;
call dolog(concat('node id-->', NEW.nid));
IF(NEW.type = 'review') THEN
    call dolog(concat('type-->', NEW.type));
    OPEN cur;
        ins_loop: LOOP
            FETCH cur INTO ratings, property_id;
            call dolog(concat('ratings -->', ratings));
            call dolog(concat('property_id -->', property_id));
            IF NOT(EXISTS(SELECT 1 FROM average_rating_property WHERE (pid = property_id))) THEN
              INSERT INTO average_rating_property (pid,total_ratings,total_count) VALUES (property_id, ratings, 1);
            ELSE
              UPDATE average_rating_property SET total_ratings = total_ratings + ratings AND total_count = total_count + 1  WHERE pid = property_id;
                call dolog('at update');
            END IF;
        END LOOP;
    CLOSE cur;
END IF;
END

If I provide static value instead of NEW.nid at line no.4 then I am getting records and loop is working, else loop is not working. It means NEW.nid is not working in cursor. But it is working while logging at line no. 7.

Is there any mistake in my code?

Best Answer

Don't use a CURSOR in a Trigger.

Do use INSERT ... ON DUPLICATE KEY UPDATE ... instead of your select+insert/update.

IODKU can handle multiple rows at once, but I don't see why that would happen. Perhaps Cursor's SELECT belongs there?

A typical pattern is:

INSERT INTO tbl (...)
    SELECT ...
    ON DUPLICATE KEY UPDATE
        a = VALUES(a), ...