0

Consider the following schema:

Table 1: Schedule_items

id | id_schedule | id_element | id_type | id_parent | creation_time

Table 2: Schedule_items_tree

id_rel | id_schedule | descendant | ancestor | depth | sequence

A goal of the second table is to store relations between schedule items. In order to make it possible, whenever I add a new row to Table 1, after-insert trigger is fired up and new rows are added to Table 2. The trigger has 3 steps:

  1. Add self-relation;
  2. Add relation between new item and given parent
  3. Add relation between new item and all descendants (based on item's parent).

Currently I do have a problem with step 2, which looks like this:

-- STEP 2: RELATION BETWEEN NEW ITEM AND GIVEN PARENT

        SELECT max(`sequence`)+1 INTO @v_seq FROM `schedule_items_tree` WHERE `id_schedule` = new.`id_schedule` AND `descendant` = new.`id_parent`;

        IF(v_seq IS NULL) THEN

            INSERT INTO `test` (`text`) VALUES ("Trigger forced sequence number to 1");
            SET v_seq = 1;

        END IF;

        -- proceed only if ancestor is not the same as descendant (self reference)
        IF(new.`id_parent` IS NOT NULL AND new.`id_element` != new.`id_parent`) THEN

            INSERT INTO `schedule_items_tree` (`id_schedule`,`descendant`,`ancestor`,`depth`,`sequence`) VALUES (new.`id_schedule`, new.`id_parent`, new.`id_element`, 1, v_seq);
        END IF;
    -- END OF STEP 2

Query SELECT max(sequence)+1 returns NULL all the time (my temporaty table gets new entry everytime trigger is executed; table created for troubleshooting purposes only). This is completely weird, because execution of the same SELECT query with the same values as from trigger results with non-NULL value.

Whatever I tried (setting v_seq differently) so far ended with the same NULL result. Any hints how to make that trigger's step working?

Kuba
  • 161
  • 2
  • 7
  • 3
    `SELECT ... INTO @v_seq ... IF(v_seq IS NULL)` Of course. `v_seq` and `@v_seq` are two different variables. – Akina Jan 29 '20 at 19:39
  • Thank you for pointing out this issue. However, it did not resolve my issue. v_seq is always 1 – Kuba Jan 30 '20 at 07:50

0 Answers0