简体   繁体   English

MySQL存储过程如果存在

[英]MySQL stored procedure If exists

I'm creating a stored procedure in MySQL, and having trouble using IF EXISTS我正在 MySQL 中创建一个存储过程,但在使用 IF EXISTS 时遇到了问题

My SQL is;我的 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

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.接受的答案对我运行 MariaDB 15.1 不起作用。 It just kept evaluating the IF condition as true and trying to insert the record even if it already existed.它只是不断地将 IF 条件评估为真,并尝试插入记录,即使它已经存在。

This is what I ended up using:这就是我最终使用的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM