如果MySQL存储过程中的条件无法正确评估

时间:2018-08-23 17:57:44

标签: mysql if-statement stored-procedures

我已经在MySQL中编写了以下程序。

CREATE DEFINER=`root`@`localhost` PROCEDURE `IsUploaderLoggedIn`(
IN `inMobile` CHAR(10),
IN `inSessionID` varchar(34)
)
BEGIN
DECLARE isLoggedIn TINYINT(1) DEFAULT 0;
DECLARE uploaderType VARCHAR(10) DEFAULT '';
CALL GetUploaderType(inMobile, @x);
SELECT @x INTO uploaderType;
IF uploaderType = "surveyor" THEN
    SELECT Count(*) INTO isLoggedIn FROM surveyors WHERE Mobile = inMobile AND SessionID = inSessionID;
    SELECT "surveyor";
ELSE
    SELECT Count(*) INTO isLoggedIn FROM uploaders WHERE Mobile = inMobile AND SessionID = inSessionID;
    SELECT "uploader";
END IF;
SELECT isLoggedIn;
END;

Navicat 中执行该过程时,对于给定值inMobileinSessionID,返回的值为:

结果1:用户类型|验船师

结果1(2):上传者|上传器

结果1(3):0或1(视情况而定)

结果1(2)s的值应为 surveyor |验船师

下面是存储过程GetUploaderType的定义:

CREATE DEFINER=`root`@`localhost` PROCEDURE `GetUploaderType`(
IN `inMobile` CHAR(10),
OUT `Usertype` VARCHAR(8)
)
BEGIN
DECLARE usertype VARCHAR(8) DEFAULT '';
DECLARE userExists TINYINT DEFAULT 0;
/*SET officeExists = 0;*/
/* Check if mobile number belongs to a surveyor */
SELECT Count(*) INTO userExists FROM surveyors WHERE Mobile = inMobile;
IF userExists = 1 THEN
    SET usertype = 'surveyor';
ELSE
    /* If user is not surveyor, check for it in uploaders */
    SELECT Count(*) INTO userExists FROM uploaders WHERE Mobile = inMobile;
    IF userExists = 1 THEN
        SET usertype = 'uploader';
    END IF;
END IF;
SELECT usertype;

END

我的脚本有什么问题吗?

1 个答案:

答案 0 :(得分:0)

GetUploaderType中,您重新声明了变量Usertype,从而隐藏了同名的(不同的)out变量,请参见scope

  

局部变量的范围是在其内声明的BEGIN ... END块。可以在声明块内嵌套的块中引用该变量,但那些声明了具有相同名称的变量的块除外。