1

I created a stored procedure which requirement as below

When I execute the stored procedure with one username typed in which be compare if username are exists in database then (variable) result_userId will set at userId ELSE if username dose not exists in database then (variable) result_userId will be set the number 99

BUT I CANNOT DO THAT

Please help me !

::CODE BELOW::

DELIMITER $$
USE `shoppy` $$
CREATE PROCEDURE `testProc02`
(
    IN  _username  CHAR(50),
    OUT result_userId   INT UNSIGNED
)
BEGIN
    SELECT @uId := userId FROM user 
    WHERE userName = _username;
    IF @uId = NULL THEN
        SET result_userId = 99;
    ELSE
        SET result_userId = @uId;
    END IF;    
END $$
DELIMITER ;

When I CALL testProc02();

enter image description here

1 Answer 1

3

You can't use the equality operator = on null. You have to test the expression IS NULL or use the null-safe equality operator <=>.

Your code should be

DELIMITER $$
USE `shoppy` $$
CREATE PROCEDURE `testProc02`
(
    IN  _username  CHAR(50),
    OUT result_userId   INT UNSIGNED
)
BEGIN
    SELECT @uId := userId FROM user 
    WHERE userName = _username;
    IF @uId IS NULL THEN
        SET result_userId = 99;
    ELSE
        SET result_userId = @uId;
    END IF;    
END $$
DELIMITER ;

What happens is that @uID = NULL always evaluates to null, which the if interprets as false.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, because my WorkBench cannot refesh the result_userId so i verry hard for testing this codes i dont know why my Workbench is only show the latest result number T_T whether i try to do hard tried

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.