I'm creating a stored procedure in MySQL, and having trouble using IF EXISTS
CREATE DEFINER=`##`@`%` PROCEDURE `myTestProceedure`(IN _id INT)
BEGIN
IF EXISTS (SELECT * FROM cms.variables WHERE tmplvarid = 5 and id = _id) THEN
BEGIN
UPDATE cms.variables SET value = now() WHERE id = _id and tmplvarid = 5;
END;
ELSE
BEGIN
INSERT INTO cms.variables (`tmplvarid`, `contentid`, `value`) VALUES (5, _id, now());
END;
END IF;
END
try this:
CREATE DEFINER=`##`@`%` PROCEDURE `myTestProceedure`(IN _id INT)
BEGIN
IF (SELECT count(*) FROM cms.variables WHERE tmplvarid = 5 and id = _id)>0 THEN
BEGIN
UPDATE cms.variables SET value = now() WHERE id = _id and tmplvarid = 5;
END;
ELSE
BEGIN
INSERT INTO cms.variables (`tmplvarid`, `contentid`, `value`) VALUES (5, _id, now());
END;
END IF;
END
The accepted answer didn't work for me running MariaDB 15.1. It just kept evaluating the IF condition as true and trying to insert the record even if it already existed.
CREATE DEFINER=`ghost`@`localhost` PROCEDURE `proc_updateTable`(IN `_id` mediumint,IN `_arg2` varchar(100))
BEGIN
#Routine body goes here...
DECLARE exist DECIMAL DEFAULT 0;
SELECT COUNT(*) INTO exist FROM `database`.`tbl_example` WHERE (`tbl_example`.`ID` = _id AND `tbl_example`.`arg2` = _arg2);
IF exist < 1 THEN
BEGIN
INSERT INTO `database`.`tbl_example` VALUES (_id,_arg2);
END;
END IF;
END
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.