I am having some difficulty getting a pretty simple stored procedure right. Consider the following article table snippet:
id replaced_by baseID
1
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 !!!