How to properly loop in a stored function on MySQL?

后端 未结 2 940
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 01:49

I am having some difficulty getting a pretty simple stored procedure right. Consider the following article table snippet:

id    replaced_by     baseID
 1             


        
相关标签:
2条回答
  • 2021-01-05 02:09

    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)

    0 讨论(0)
  • 2021-01-05 02:30

    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 !!!

    0 讨论(0)
提交回复
热议问题