MySQL查找if中满足哪个条件

时间:2013-04-26 05:58:03

标签: mysql sql

好吧..这可能看起来很奇怪,但有没有办法找到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';
}

如果我得到任何解决方案,那么我将节省1000s if循环!!!

1 个答案:

答案 0 :(得分: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

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