I am working on writing a recursive stored procedure in MySQL that will return multiple rows of data, namely the data for a child and all of its parents, grandparents, etc. For example, if I have the following table ("families"):
+---------+------+------------+
| Status | Name | ParentName |
+---------+------+------------+
| healthy | A | NULL |
+---------+------+------------+
| healthy | B | NULL |
+---------+------+------------+
| healthy | C | A |
+---------+------+------------+
| healthy | D | C |
+---------+------+------------+
| healthy | E | B |
+---------+------+------------+
and I run the procedure on the name 'D', it should return the following:
+---------+------+------------+
| Status | Name | ParentName |
+---------+------+------------+
| healthy | D | C |
+---------+------+------------+
| healthy | C | A |
+---------+------+------------+
| healthy | A | NULL |
+---------+------+------------+
For now, ordering is not very important, I should be able to figure that out later. It's also worth noting that there are cases where the parent name is alphabetically greater than the child table name and some where the parent is alphabetically less than the child table name. I've seen solutions for this that require the parent to be less than the child, but those will not work for me. This would be pretty easy if I had access to a version of MySQL that supported CTEs, but unfortunately that is not possible. Instead, I'm using stored procedures recursively to solve my problem. The code I have so far is as follows:
DELIMITER |
CREATE PROCEDURE getNextLevel( IN parent_name TEXT)
BEGIN
IF parent_name IS NOT NULL
SELECT Status, Name, ParentName
FROM families
WHERE ParentName = parent_name
UNION
CALL getNextLevel(ParentName);
-- This is the line that throws an error
END IF;
END |
DELIMITER ;
Evidently, it's not as simple as just calling my procedure recursively like that (or maybe I'm just calling it wrong). Can anyone provide any insight into what I need to do here, or possibly an alternate solution for my problem?