web-dev-qa-db-fra.com

Trigger Mysql avec IF THEN

Mon stockage est INNODB, j'essaie de créer un déclencheur avec 2 requêtes dans l'instruction IF. En bas, vous pouvez voir le déclencheur qui me donne l'erreur

delimiter |
CREATE TRIGGER count_delete_videos BEFORE DELETE ON videos
  FOR EACH ROW BEGIN
    UPDATE counts SET count = count - 1 WHERE name = 'all';

    IF OLD.published = 1 THEN
        DELETE FROM videos_categories WHERE id_video = OLD.id;
        DELETE FROM videos_tags WHERE id_video = OLD.id;
    END IF;
  END;
|
delimiter ;

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= OLD.id;
    END IF;
  END' at line 6

Ce sont les 2 déclencheurs que j'active avec le premier.

delimiter |
CREATE TRIGGER count_delete_videos_tags AFTER DELETE ON videos_tags
  FOR EACH ROW BEGIN
    UPDATE tags SET count = count - 1 WHERE id = OLD.id_tag;
  END;
|
delimiter ;


delimiter |
CREATE TRIGGER count_delete_videos_categories AFTER DELETE ON videos_categories
  FOR EACH ROW BEGIN
    UPDATE categories SET count = count - 1 WHERE id = OLD.id_category;

    IF OLD.id_category <> 20 AND OLD.id_category <> 34 THEN
        UPDATE counts SET count=count-1 WHERE name='english';
    ELSEIF OLD.id_category = 34 THEN
        UPDATE counts SET count=count-1 WHERE name='german';
    ELSEIF OLD.id_category = 20 THEN
        UPDATE counts SET count=count-1 WHERE name='italian';
    END IF;
  END;
|
delimiter ;

Mais celui-ci fonctionne parfaitement

delimiter |
    CREATE TRIGGER count_delete_videos BEFORE DELETE ON videos
      FOR EACH ROW BEGIN
        UPDATE counts SET count = count - 1 WHERE name = 'all';

        IF OLD.published = 1 THEN
            DELETE FROM videos_categories WHERE id_video = OLD.id;
        END IF;
      END;
    |
    delimiter ;

Query OK, 0 rows affected (0.16 sec)

Comment faire fonctionner le premier déclencheur? qu'est-ce que je fais mal? Merci de m'aider.

13
Alex Prut

Pour autant que je sache, les deux déclencheurs sont OK, mais vous pouvez essayer ce qui suit:

DELIMITER $$
CREATE TRIGGER count_delete_videos BEFORE DELETE ON videos
FOR EACH ROW 
BEGIN
  UPDATE counts SET count = count - 1 WHERE name = 'all';

  IF OLD.published = 1 THEN BEGIN
    DELETE FROM videos_categories WHERE id_video = OLD.id;
    DELETE FROM videos_tags WHERE id_video = OLD.id;
  END; END IF;
END$$

DELIMITER ;
16