0

好的..这可能看起来很奇怪,但是有没有办法在 if 语句的多个条件中找到满足哪个条件?我正在 MySql 5.1 中编写触发器,我必须在某些条件下引发错误。我想做一些类似下面的代码,

if(new.col1 = 'A' and (new.col2 is null or new.col3 is null) {
    //if new.col1 = 'A' and **new.col2** was null
    set msg = '<col2> cannot be null';
}
if(new.col1 = 'B' and (new.col4 is null or new.col5 is null) {
    //if new.col1 = 'B'and **new.col5** was null
    set msg = '<col5> cannot be null';
}

如果我对此有任何解决方案,那么我将节省 1000 次if循环!!!

4

1 回答 1

2

您可以使用SIGNAL语句来引发错误 -

IF NEW.col1 = 'A' AND (NEW.col2 IS NULL OR new.col3 IS NULL) THEN
  SIGNAL SQLSTATE VALUE '20001' SET MESSAGE_TEXT = 'col2 cannot be null';
ELSEIF NEW.col1 = 'B' AND (NEW.col4 IS NULL OR new.col5 IS NULL) THEN
  SIGNAL SQLSTATE VALUE '20001' SET MESSAGE_TEXT = 'col5 cannot be null';
END IF;

SIGNAL 命令在 MySQL 5.5 及更高版本中可用。

当您使用 MySQL 5.1 时,您可以使用一种解决方法 -

IF NEW.col1 = 'A' AND (NEW.col2 IS NULL OR new.col3 IS NULL) THEN
  CALL `col2 cannot be null()`;
ELSEIF NEW.col1 = 'B' AND (NEW.col4 IS NULL OR new.col5 IS NULL) THEN
  CALL `col5 cannot be null()`;
END IF

在这种情况下,错误消息不会像预期的那样,但代码将被中断并引发错误。

于 2013-04-26T06:06:01.387 回答