Throw an error in a MySQL trigger

后端 未结 7 1014
-上瘾入骨i
-上瘾入骨i 2020-11-22 11:59

If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?

相关标签:
7条回答
  • 2020-11-22 13:01

    Another (hack) method (if you are not on 5.5+ for some reason) that you can use:

    If you have a required field, then within a trigger set the required field to an invalid value such as NULL. This will work for both INSERT and UPDATE. Do note that if NULL is a valid value for the required field (for some crazy reason) then this approach will not work.

    BEGIN
        -- Force one of the following to be assigned otherwise set required field to null which will throw an error
        IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN
            SET NEW.`required_id_field`=NULL;
        END IF;
    END
    

    If you are on 5.5+ then you can use the signal state as described in other answers:

    BEGIN
        -- Force one of the following to be assigned otherwise use signal sqlstate to throw a unique error
        IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN
            SIGNAL SQLSTATE '45000' set message_text='A unique identifier for nullable_field_1 OR nullable_field_2 is required!';
        END IF;
    END
    
    0 讨论(0)
提交回复
热议问题