好吧..这可能看起来很奇怪,但是有没有办法找到 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
循环!!!
最佳答案
您可以使用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
在这种情况下,错误消息不会按预期显示,但代码将被中断并引发错误。
关于MySQL 查找 if 中满足哪个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16229672/