MySQL Procedure check if record exists before insert not working

KacieHouser picture KacieHouser · Aug 30, 2012 · Viewed 14k times · Source

I have looked at the other questions on here about this. It isn't working.

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `environment_admin`(
IN environment_id   TEXT,
IN user_id          TEXT,
IN username         VARCHAR(75),
IN password         VARCHAR(512)
)
BEGIN
DECLARE env_id INT;
DECLARE admin_id INT;

SET env_id = CAST(environment_id AS SIGNED INT);
SET admin_id = CAST(user_id AS SIGNED INT);

IF NOT EXISTS(SELECT 1 FROM `environment`.`environment_accounts` WHERE environment_id = env_id AND user_id = admin_id) THEN
    BEGIN
    INSERT INTO 
        `environment`.`environment_accounts` 
        (
            `environment_id`, 
            `user_id`, 
            `username`, 
            `password`, 
            `is_active`, 
            `is_admin`, 
            `is_mod`
        ) 
        VALUES 
        (
            env_id, 
            admin_id,
            username,
            password,
            1,
            1,
            1
        );
    END;
END IF;
END

So if I run:

CALL `environment`.`environment_admin`('22','1','kacieh','512c9ad228332bbd30d09ce7ffb8896e00a1610e914a5fa180bf15ce702b90423e6a9540579f672315ae3c6cb1b8d06ee2b784b4761e806675aa88c2a915553e');

I get 0 row(s) effected and sure enough, nothing happened. -_- I have been working on this hours I tested the conditional query, it works. I have tested just the insert statement inside a stored proc, it works as well.

Answer

Parallelis picture Parallelis · Aug 30, 2012

Stop doing it like that, it's inefficient and it could be worse if two insertare running concurrently! :)

Use INSERT.... ON DUPLICATE KEY UPDATE ... see here

One trick is to do ON DUPLICATE KEY UPDATE environment_id = env_id (not changing the column, so nothing will be updated, ensuring the INSERT will not work without any error condition, you might check number of modified/inserted rows after that)