How to properly loop in a stored function on MySQL?

丶灬走出姿态 提交于 2019-11-30 19:43:33

From mysql :

If the query returns no rows, a warning with error code 1329 occurs (No data), and the variable values remain unchanged

So you have an infinite loop when no records found with a given x (y remains unchanged) Try SET y = (SELECT id ....) instead or add SET y = null before your select statement (it should be the first statement in the loop)

It feels like you may be missing an index on the replaced_by column. If there no index on replaced_by, you are looking at a full table scan with every iteration.

ALTER TABLE article ADD INDEX (replaced_by);

You should also make sure the row exists before retrieving

DELIMITER $$

CREATE FUNCTION getBaseID(articleID INT) RETURNS INT
BEGIN
    DECLARE x INT;
    DECLARE y INT;
    SET x = articleID;
    sloop:LOOP
        SELECT COUNT(1) INTO y FROM article WHERE replaced_by = x;
        IF y > 0 THEN
            SELECT id INTO y FROM article WHERE replaced_by = x;
            SET x = y;
        ELSE
            LEAVE sloop;
        END IF;  
    END LOOP;
    RETURN x;
END $$

DELIMITER ;

Twice as many SQL calls but better safe than sorry.

Give it a Try !!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!