IF语法

IF和END IF是成对出现

使用ELSEIF的时候,要特别注意,由于平时用习惯ELSE IF(即中间多个空格),所以这里很容易出错,而且出错信息很奇怪,记住:中间没有空格。

  1. IF search_condition THEN statement_list
  2. [ELSEIF search_condition THEN statement_list] ...
  3. [ELSE statement_list]
  4. END IF
  1. DELIMITER //
  2. CREATE FUNCTION SimpleCompare(n INT, m INT)
  3. RETURNS VARCHAR(20)
  4. BEGIN
  5. DECLARE s VARCHAR(20);
  6. IF n > m THEN SET s = '>';
  7. ELSEIF n = m THEN SET s = '=';
  8. ELSE SET s = '<';
  9. END IF;
  10. SET s = CONCAT(n, ' ', s, ' ', m);
  11. RETURN s;
  12. END //
  13. DELIMITER ;
  1. DELIMITER //
  2. CREATE FUNCTION VerboseCompare (n INT, m INT)
  3. RETURNS VARCHAR(50)
  4. BEGIN
  5. DECLARE s VARCHAR(50);
  6. IF n = m THEN SET s = 'equals';
  7. ELSE
  8. IF n > m THEN SET s = 'greater';
  9. ELSE SET s = 'less';
  10. END IF;
  11. SET s = CONCAT('is ', s, ' than');
  12. END IF;
  13. SET s = CONCAT(n, ' ', s, ' ', m, '.');
  14. RETURN s;
  15. END //
  16. DELIMITER ;

原文: https://strongyoung.gitbooks.io/mysql-reference-manual/content/sql_statement_syntax/mysql_compound_statement_syntax/flow_control_statement/if_syntax.html