在MySQL触发器中抛出错误

Matt MacLean 156 mysql database triggers

如果我有一个trigger before the update表,我怎么能抛出一个阻止该表更新的错误?

RuiDC.. 128

从MySQL 5.5开始,您可以使用SIGNAL语法抛出异常:

signal sqlstate '45000' set message_text = 'My Error Message';

状态45000是表示"未处理的用户定义的异常"的通用状态.


以下是该方法的更完整示例:

delimiter //
use test//
create table trigger_test
(
    id int not null
)//
drop trigger if exists trg_trigger_test_ins //
create trigger trg_trigger_test_ins before insert on trigger_test
for each row
begin
    declare msg varchar(128);
    if new.id < 0 then
        set msg = concat('MyTriggerError: Trying to insert a negative value in trigger_test: ', cast(new.id as char));
        signal sqlstate '45000' set message_text = msg;
    end if;
end
//

delimiter ;
-- run the following as seperate statements:
insert into trigger_test values (1), (-1), (2); -- everything fails as one row is bad
select * from trigger_test;
insert into trigger_test values (1); -- succeeds as expected
insert into trigger_test values (-1); -- fails as expected
select * from trigger_test;


Justin.. 57

这是一个可行的黑客.它不干净,但它看起来可能有效:

实质上,您只是尝试更新不存在的列.


el.atomo.. 30

不幸的是,@ Ryui提供的答案在5.5之前的MySQL版本中不起作用,因为存储过程没有SIGNAL的实现.

发现的解决方案是模拟抛出table_name doesn't exist错误的信号,将自定义的错误消息推送到table_name.

可以使用触发器或使用存储过程来实现hack.我按照@RuiDC使用的示例描述了下面的两个选项.

使用触发器

DELIMITER $$
-- before inserting new id
DROP TRIGGER IF EXISTS before_insert_id$$
CREATE TRIGGER before_insert_id
    BEFORE INSERT ON test FOR EACH ROW
    BEGIN
        -- condition to check
        IF NEW.id < 0 THEN
            -- hack to solve absence of SIGNAL/prepared statements in triggers
            UPDATE `Error: invalid_id_test` SET x=1;
        END IF;
    END$$

DELIMITER ;

使用存储过程

存储过程允许您使用动态sql,这使得可以在一个过程中封装错误生成功能.对应的是我们应该控制应用程序插入/更新方法,因此它们只使用我们的存储过程(不授予对INSERT/UPDATE的直接权限).

DELIMITER $$
-- my_signal procedure
CREATE PROCEDURE `my_signal`(in_errortext VARCHAR(255))
BEGIN
    SET @sql=CONCAT('UPDATE `', in_errortext, '` SET x=1');
    PREPARE my_signal_stmt FROM @sql;
    EXECUTE my_signal_stmt;
    DEALLOCATE PREPARE my_signal_stmt;
END$$

CREATE PROCEDURE insert_test(p_id INT)
BEGIN
    IF NEW.id < 0 THEN
         CALL my_signal('Error: invalid_id_test; Id must be a positive integer');
    ELSE
        INSERT INTO test (id) VALUES (p_id);
    END IF;
END$$
DELIMITER ;


Marinos An.. 11

以下过程(在mysql5上)是一种抛出自定义错误并同时记录它们的方法:

create table mysql_error_generator(error_field varchar(64) unique) engine INNODB;
DELIMITER $$
CREATE PROCEDURE throwCustomError(IN errorText VARCHAR(44))
BEGIN
    DECLARE errorWithDate varchar(64);
    select concat("[",DATE_FORMAT(now(),"%Y%m%d %T"),"] ", errorText) into errorWithDate;
    INSERT IGNORE INTO mysql_error_generator(error_field) VALUES (errorWithDate);
    INSERT INTO mysql_error_generator(error_field) VALUES (errorWithDate);
END;
$$
DELIMITER ;


call throwCustomError("Custom error message with log support.");


BHUVANESH MO.. 6

CREATE TRIGGER sample_trigger_msg 
    BEFORE INSERT
FOR EACH ROW
    BEGIN
IF(NEW.important_value) < (1*2) THEN
    DECLARE dummy INT;
    SELECT 
           Enter your Message Here!!!
 INTO dummy 
        FROM mytable
      WHERE mytable.id=new.id
END IF;
END;