在MySQL触发器中引发错误


Answers:


60

这是一种可行的技巧。这不是干净的,但看起来可能可行:

本质上,您只是尝试更新不存在的列。


1
您好,您可以举一个实际的示例来说明如何在链接中编写触发器吗?我有两列(idUser和idGuest)在表顺序中必须互斥,但是我对触发器还是比较陌生,并且发现了很多困难写吧!谢谢。
Nicola Peluchetti 2011年

147

从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;

34

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

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

黑客可以使用触发器或存储过程来实现。我将在@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 ;

在过程insert_test中,如果new.id <0无效,则语法无效,如果P_id <0
蒂姆·

1
@happy_marmoset,不是要提出一个错误吗?通过使用错误文本作为表名,将触发错误并防止插入。据我了解,这是一种方法,如果您的mysql <5.5
Jette

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.");

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;

尽管此代码段可以解决问题,但提供说明确实有助于提高您的帖子质量。请记住,您将来会为读者回答这个问题,而这些人可能不知道您提出代码建议的原因。也请尽量不要在代码中添加解释性注释,因为这会降低代码和解释的可读性!
再见StackExchange,

5

可以使用的另一种(hack)方法(如果您由于某种原因未使用5.5+):

如果您具有必填字段,则在触发器内,将必填字段设置为无效值,例如NULL。这对于INSERT和UPDATE均适用。请注意,如果NULL是必填字段的有效值(出于某种疯狂的原因),则此方法将不起作用。

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

如果您使用的是5.5+,则可以使用其他答案中所述的信号状态:

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
DELIMITER @@
DROP TRIGGER IF EXISTS trigger_name @@
CREATE TRIGGER trigger_name 
BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN

  --the condition of error is: 
  --if NEW update value of the attribute age = 1 and OLD value was 0
  --key word OLD and NEW let you distinguish between the old and new value of an attribute

   IF (NEW.state = 1 AND OLD.state = 0) THEN
       signal sqlstate '-20000' set message_text = 'hey it's an error!';     
   END IF;

END @@ 
DELIMITER ;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.