在MySQL中,如何为此错误消息创建自定义消息:
无法删除或更新父行:外键约束失败 (
database
。jenis_fasum
,CONSTRAINTjenis_fasum_ibfk_1
FOREIGN KEY (id_kategori
)参考kategori_fasum
(id_kategori
))
使用触发器可能吗?有人可以提供一个例子吗?
感谢您的帮助
答案 0 :(得分:2)
我不认为可以在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)
顺便问一下,你为什么要这个?