USE testdb;DELIMITER $$CREATEPROCEDURE insert_article_tags(IN article_id INT, IN tag_id INT)BEGINDECLARECONTINUE HANDLER FOR1062SELECTCONCAT('duplicate keys (',article_id,',',tag_id,') found') AS msg;-- insert a new record into article_tagsINSERT INTO article_tags(article_id,tag_id)VALUES(article_id,tag_id);-- return tag count for the articleSELECTCOUNT(*) FROM article_tags;END$$DELIMITER ;
DELIMITER $$CREATEPROCEDURE insert_article_tags_exit(IN article_id INT, IN tag_id INT)BEGINDECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT'SQLException invoked';DECLARE EXIT HANDLER FOR1062SELECT'MySQL error code 1062 invoked';DECLARE EXIT HANDLER FOR SQLSTATE '23000'SELECT'SQLSTATE 23000 invoked';-- insert a new record into article_tagsINSERT INTO article_tags(article_id,tag_id)VALUES(article_id,tag_id);-- return tag count for the articleSELECTCOUNT(*) FROM article_tags;END $$DELIMITER ;
执行上面查询语句,得到以下结果 -
mysql>CALL insert_article_tags_exit(1,3);+-------------------------------+| MySQL error code 1062 invoked |+-------------------------------+| MySQL error code 1062 invoked |+-------------------------------+1rowinsetQuery OK, 0rows affected
DELIMITER $$CREATEPROCEDURE insert_article_tags_3(IN article_id INT, IN tag_id INT)BEGINDECLARE EXIT HANDLER FOR1062SELECT'Duplicate keys error encountered';DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT'SQLException encountered';DECLARE EXIT HANDLER FOR SQLSTATE '23000'SELECT'SQLSTATE 23000';-- insert a new record into article_tagsINSERT INTO article_tags(article_id,tag_id)VALUES(article_id,tag_id);-- return tag count for the articleSELECTCOUNT(*) FROM article_tags;END $$DELIMITER ;