简体   繁体   中英

MySQL Stored Procedure - IF EXISTS … THEN returning unexpected result

The below is my Stored Procedure(Routine) to check whether or not a user with Username(input) exists in the database. Inside the database, I already have a user with Username - 'dev'. However, when I ran the below routine, it returned me with res = 1 , which I expected it to be -1 .

I called the routine this way. Please correct me too if I am calling it the wrong way. I am really new to MySQL Routines.

CALL usp_GetUserValidation ('dev', @ErrorCode)

Can any MySQL Routine pros here enlighten me on this? Thank you in advance guys :)

DELIMITER $$
CREATE PROCEDURE usp_GetUserValidation(IN `@Username` VARCHAR(255), OUT `@ErrorCode` INT)
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT 'To validate user login'
BEGIN

    IF EXISTS
    (SELECT UserID 
        FROM mt_User
        WHERE UserName = @Username)
    THEN
            SET @ErrorCode = -1;


    ELSE
        SET @ErrorCode =  1;

    END IF;


    SELECT @ErrorCode AS res;

END$$
DELIMITER ;

It was simply your naming conventions for the parameters. It is finicky and does not like User Variable @ signs in them.

You are just testing I can see, as you are returning both a resultset with the info and the OUT variable.

drop procedure if exists usp_GetUserValidation;
DELIMITER $$
CREATE PROCEDURE usp_GetUserValidation(IN pUsername VARCHAR(255), OUT pErrorCode INT)
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT 'To validate user login'
BEGIN

    IF EXISTS
    (SELECT UserID 
        FROM mt_User
        WHERE UserName = pUsername)
    THEN
            SET pErrorCode = -1;
    ELSE
        SET pErrorCode =  1;
    END IF;


    SELECT pErrorCode AS res;

END$$
DELIMITER ;

Schema:

-- drop table if exists mt_user;
create table mt_User 
(   UserID int auto_increment primary key,
    UserName varchar(100) not null,
    unique key(UserName)
);

insert mt_User(UserName) values ('dev');
select * from mt_User;

Test:

set @var1:=-4;
call usp_GetUserValidation('dev',@var1);
-- returns (-1) ---- Yea, we like that
select @var1;
-- (-1)

set @var1:=-4;
call usp_GetUserValidation('dev222',@var1);
-- returns 1 ---- Yea, we like that
select @var1;
-- 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM