user4383363
user4383363

Reputation:

MySQL trigger after insert delete query not working

I have the following trigger, created in phpMyAdmin:

Table: tb_agenda Time: AFTER Event: INSERT

BEGIN
    DECLARE x INT DEFAULT 0;
    DECLARE i INT DEFAULT 0;

    SELECT COUNT(*) FROM tb_agenda INTO x;

    SET i = 0;

    WHILE i < x DO
        INSERT INTO tb_realizacao (dt_agenda,
                                   titulo, 
                                   titulo_en, 
                                   descricao, 
                                   descricao_en, 
                                   dt_cadastro)
        SELECT  dt_agenda,
                titulo,
                titulo_en,
                descricao,
                descricao_en,
                dt_cadastro
        FROM tb_agenda
        WHERE dt_agenda < NOW();

        DELETE FROM tb_agenda
         WHERE dt_agenda < NOW();

        SET i = i + 1;
    END WHILE;
END

What's this: after inserting into tb_agenda, it's supposed to search for data which dt_agenda (date) is lower than NOW(), add into tb_realizacao and then delete this old data from tb_agenda. The problem is that the delete query seems not to be executed, the data is normally added into the tb_realizacao but not deleted from tb_agenda.

Upvotes: 0

Views: 328

Answers (1)

Volt
Volt

Reputation: 99

No need to set WHERE since NOW means that all of them will be removed. No need for WHILE since every trigger has FOR EACH ROW. You cannot delete from table where you insert so delete will be in the php script.

php script:

$pdo->query("DELETE FROM tb_agenda");
$pdo->query("INSERT ...");

trigger: Table: tb_agenda Time: BEFORE Event: DELETE

BEGIN
    INSERT INTO tb_realizacao (dt_agenda,
                               titulo, 
                               titulo_en, 
                               descricao, 
                               descricao_en, 
                               dt_cadastro)
    VALUES  (OLD.dt_agenda,
            OLD.titulo,
            OLD.titulo_en,
            OLD.descricao,
            OLD.descricao_en,
            OLD.dt_cadastro);

END;

Upvotes: 0

Related Questions