質問

I'm creating a stored procedure in MySQL, and having trouble using IF EXISTS

My SQL is;

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

Basically, what I'm trying to do in this procedure is IF the row already exists in the DB, update it, otherwise insert it.

However despite whatever result SELECT * FROM cms.variables WHERE tmplvarid = 5 and id = _id gives, it just inserts into the database.

Any help would be greatly appreciated.

役に立ちましたか?

解決

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.

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

Hope this helps someone else with this problem

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top