我在MySQL中创建存储过程,并且在使用IF EXISTS时遇到问题
我的SQL是;
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
基本上,我在这个过程中尝试做的是如果该行已存在于DB中,请更新它,否则插入它。
然而,尽管SELECT * FROM cms.variables WHERE tmplvarid = 5 and id = _id
给出了结果,但它只是插入到数据库中。
非常感谢任何帮助。
答案 0 :(得分:6)
试试这个:
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