1
DELIMITER $$
DROP PROCEDURE IF EXISTS `user_db`.`insertUser` $$
CREATE PROCEDURE `user_db`.`insertUser`(
    IN _userEmail VARCHAR(50),
    IN _userPassword VARCHAR(50),
    IN _userPhone VARCHAR(10),
    IN _userUsername VARCHAR(50),
    IN _userAccountType ENUM('0', '1'),
    IN _userAdmin ENUM('0', '1'),
    IN _userSuperAdmin ENUM('0', '1'),
    IN _userPresenceState ENUM('0', '1'),
    OUT _userInsertResult INT(36)
)
NOT DETERMINISTIC MODIFIES SQL DATA SQL SECURITY DEFINER
BEGIN
    DECLARE _userCount INT;

    SELECT COUNT(id) AS _userCount FROM `user_db`.`user_primary` WHERE email = _userEmail LIMIT 1;

    IF _userCount = 0 THEN

    INSERT INTO `user_db`.`user_primary` (id, email, encrypted_password, phone, username, user_account_type, user_admin, user_super_admin, presence_state) VALUES (UUID(), _userEmail, _userPassword, _userPhone, _userUsername, _userAccountType, _userAdmin, _userSuperAdmin, _userPresenceState);
    SET _userInsertResult := LAST_INSERT_ID();

    END IF;
END
$$
DELIMITER ;

I wrote this stored procedure in MYSQL to check if the user exist and if the count is 0 then insert and return the id else I'll do something else. But even if the _userCount is 0, the INSERT statement is not working. This is my first stored procedure and I'm learning. I'm trying but not able to understand the reason for failure.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Subrata Banerjee
  • 299
  • 1
  • 5
  • 21

2 Answers2

3

You want:

SELECT COUNT(id) INTO _userCount FROM ...

Merely using AS just declares a column alias for the COUNT(id) expression, it doesn't assign the result to a variable of the same name as the alias.

So in your procedure, the variable _userCount is never assigned a value, and so the statement inside your IF block never runs.

P.S.: This has nothing to do with your question, but I noticed you are using INT(36). The argument to INT doesn't do anything. It doesn't make the INT larger or able to accept 36-digit numbers. See my answer to Types in MySQL: BigInt(20) vs Int(20)

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
0

An alternative answer is to tweak your logic a bit, replacing this

SELECT COUNT(id) AS _userCount 
FROM `user_db`.`user_primary` 
WHERE email = _userEmail LIMIT 1;

IF _userCount = 0 THEN

with

IF NOT EXISTS (SELECT * FROM `user_db`.`user_primary` WHERE email = _userEmail) THEN
Uueerdo
  • 15,723
  • 1
  • 16
  • 21