سؤال

I know mysql 5.5 allows using SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Error: ...'; to raise a user defined error. And this error will stop an INSERT operation if it was put in the BEFORE INSERT TRIGGER on some tables. And it's also convenient for PDO to catch the PDOException and output the errorinfo() i.e. MESSAGE_TEXT defined in SIGNAL SQLSTATE.
However, the version of mysql on the server I rent is mysql 5.1. And I want to know how can I raise a user defined error with the features like the SIGNAL SQLSTATEMENT in mysql 5.5.

  1. interrupt a insert operation when it's in before insert trigger
  2. can be caught by PDO

I've found some topics on similar problems, and I've tried these:

  • call a nonexist procedure

    call `sp_raise_error`;

  • use a function to throw an error

https://blogs.oracle.com/svetasmirnova/entry/how_to_raise_error_in

Both can't be caught by PDO. So what's a solution? ( I tested on MySQL5.5 )

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top