6

在 MySQL 中,如何为此错误消息创建自定义消息:

无法删除或更新父行:外键约束失败 ( database. jenis_fasum, CONSTRAINT jenis_fasum_ibfk_1FOREIGN KEY ( id_kategori) REFERENCES kategori_fasum( id_kategori))

也许使用触发器?有人可以提供一个例子吗?

谢谢你的帮助

4

1 回答 1

5

我不认为它可以在 a 中完成TRIGGER,但可以通过 MySQL 5.5 中的存储过程完成。

这是默认错误消息:

mysql> INSERT INTO area SET location_id = 'invalid';
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`rates`.`area`, CONSTRAINT `area_ibfk_1` FOREIGN KEY (`location_id`) REFERENCES `location` (`id`))

mysql> SHOW ERRORS;
+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Level | Code | Message                                                                                                                                                              |
+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Error | 1452 | Cannot add or update a child row: a foreign key constraint fails (`rates`.`area`, CONSTRAINT `area_ibfk_1` FOREIGN KEY (`location_id`) REFERENCES `location` (`id`)) |
+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

这是我们的存储过程:

DROP PROCEDURE IF EXISTS test1;

DELIMITER //

CREATE PROCEDURE test1()
DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY INVOKER
BEGIN
  DECLARE EXIT HANDLER FOR SQLSTATE '23000'
  BEGIN
    SIGNAL SQLSTATE '23000' SET 
      MYSQL_ERRNO = 1452,
      MESSAGE_TEXT = 'Yo! Error 23000!';
  END;

  INSERT INTO area SET location_id = 'invalid';
END;
//

DELIMITER ;

这是我们的自定义错误消息:

mysql> CALL test1();
ERROR 1452 (23000): Yo! Error 23000!

mysql> SHOW ERRORS;
+-------+------+------------------+
| Level | Code | Message          |
+-------+------+------------------+
| Error | 1452 | Yo! Error 23000! |
+-------+------+------------------+
1 row in set (0.00 sec)

顺便说一句,你为什么要这个?

于 2012-08-01T06:01:59.540 回答