MySQL:存储过程中的IF

时间:2012-03-10 20:13:07

标签: mysql stored-procedures

我刚刚用存储过程弄湿了脚。根据我看到的教程,这应该是有效的(MySQL 5.5):

CREATE PROCEDURE someFunction ( a VARCHAR(256),  b VARCHAR(256) )
    BEGIN
        DECLARE haveAllVariables INT;
        SET haveAllVariables = 1;

    IF     a = "" THEN SET haveAllVariables = 0
    ELSEIF b = "" THEN SET haveAllVariables = 0
    END IF;

然而,它抛出了这个错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'ELSEI
F b = "" THEN SET haveAllVariables = 0

我的语法错误在哪里?

感谢。

2 个答案:

答案 0 :(得分:16)

你错过了分号

CREATE PROCEDURE someFunction ( a VARCHAR(256),  b VARCHAR(256) )
    BEGIN
        DECLARE haveAllVariables INT;
        SET haveAllVariables = 1;

    IF     a = "" THEN SET haveAllVariables = 0;
    ELSEIF b = "" THEN SET haveAllVariables = 0;
    END IF;

答案 1 :(得分:6)

存储过程有点棘手。但这是我测试并发布给你的一个例子。在你的例子中,你错过了几个分号和最后的“结束”。

DELIMITER $$
  CREATE PROCEDURE someFunction ( a VARCHAR(256),  b VARCHAR(256) )
  BEGIN
    DECLARE haveAllVariables INT;
    SET haveAllVariables = 1;

  IF  a = '' THEN 
    SET haveAllVariables = 0;
  ELSEIF b = '' THEN 
    SET haveAllVariables = 0;
  END IF;
END $$