mysql 自定义错误码,创建自定义错误消息MySQL

In MySQL, how to create custom message for this error message:

Cannot delete or update a parent row: a foreign key constraint fails

(database.jenis_fasum, CONSTRAINT jenis_fasum_ibfk_1 FOREIGN KEY

(id_kategori) REFERENCES kategori_fasum (id_kategori))

Using trigger maybe? Can someone provide an example?

Thanks for your help

解决方案

I don't think it can be done in a TRIGGER, but it can be done with a stored procedure in MySQL 5.5.

Here's the default error message:

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)

And here's our stored procedure:

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 ;

And here's our custom error message:

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)

By the way, why do you want this?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值