If you use SIGNAL SQLSTATE
in a lower version of MySQL (like 5.1), you will get a 1064
error. So, in order to use the function like SIGNAL SQLSTATE
does, you can try the following steps.
1. Create Auxiliary Table Named "TBL_DUMMY"
CREATE TABLE IF NOT EXISTS `TBL_DUMMY`
(
`error` VARCHAR(256)
);
2. Create BEFORE INSERT Trigger on TBL_DUMMY
delimiter $$
CREATE TRIGGER `TRIG_BI_DUMMY` BEFORE INSERT ON `TBL_DUMMY`
FOR EACH ROW
BEGIN
SET NEW = NEW.`error`;
END $$
3. Create Procedure Named "SP_RAISE_ERROR"
delimiter $$
CREATE PROCEDURE `SP_RAISE_ERROR` (IN P_ERROR VARCHAR(256))
BEGIN
DECLARE V_ERROR VARCHAR(300);
SET V_ERROR := CONCAT('[ERROR: ', P_ERROR, ']');
INSERT INTO `TBL_DUMMY` VALUES (V_ERROR);
END $$
4. Usage
Just execute SP_RAISE_ERROR
instead of SIGNAL SQLSTATE
. For instance, CALL SP_RAISE_ERROR ('Password incorrect.')
will throw an exception and the message is:
0 15:40:23 CALL SP_RAISE_ERROR ('Password incorrect.') Error Code: 1231. Variable 'new' can't be set to the value of '[ERROR: Password incorrect.]'.
And you can use it in procedures:
IF V_ID IS NOT NULL AND V_ID <> P_ID THEN
CALL `SP_RAISE_ERROR` ('Title duplicated.');
END IF;
After that, you can extract error texts from the messages in an external program.