I'm trying to create a function in mysql which will return boolean if the id already exist in the table. Most of the solutions that I found online require solutions using both php and mysql but what I'm trying to do is a solution purely in mysql in the form of a function.
My simplifed mysql table will be as follow:
CREATE TABLE IF NOT EXISTS table1 (
`user_id` VARCHAR(12) UNIQUE,
`name` VARCHAR(128),
PRIMARY KEY (`user_id`)
);
My first attempt was below:
DELIMITER *
DROP FUNCTION IF EXISTS CheckExistId*
CREATE FUNCTION CheckExistId (user_id VARCHAR(12)) RETURNS BOOL
BEGIN
DECLARE isExist BOOL;
SET isExist = 0;
SELECT EXISTS(SELECT * FROM table1 WHERE `user_id`=user_id) INTO isExist ;
RETURN isExist;
END*
DELIMITER ;
My second attempt:
DELIMITER *
DROP FUNCTION IF EXISTS CheckExistId*
CREATE FUNCTION CheckExistId (user_id VARCHAR(12)) RETURNS BOOL
BEGIN
DECLARE isExist BOOL;
DECLARE countRow INT;
SELECT COUNT(`user_id`) INTO countRow FROM table1 WHERE `user_id`=user_id;
IF countRow = 0 THEN SET isExist = 1;
ELSE SET isExist = 0;
END IF;
RETURN isExist;
END*
DELIMITER ;
Both didn't give me the result that I expected. Any suggestions on how to fix this?