Created
May 2, 2014 05:54
-
-
Save vrushank-snippets/603919ac6030c3379ee0 to your computer and use it in GitHub Desktop.
MySQL : GetAncestry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
----------GET ANCESTORS MYSQL CUSTOM FUNCTION------ | |
DELIMITER $$ | |
DROP FUNCTION IF EXISTS `GetAncestry` $$# MySQL returned an empty result set (i.e. zero rows). | |
CREATE FUNCTION `GetAncestry` (GivenID INT) RETURNS VARCHAR(1024) | |
DETERMINISTIC | |
BEGIN | |
DECLARE rv VARCHAR(1024); | |
DECLARE cm CHAR(1); | |
DECLARE ch INT; | |
SET rv = ''; | |
SET cm = ''; | |
SET ch = GivenID; | |
WHILE ch > 0 DO | |
SELECT IFNULL(parent_id,-1) INTO ch FROM | |
(SELECT parent_id FROM category WHERE id = ch) A; | |
IF ch > 0 THEN | |
SET rv = CONCAT(rv,cm,ch); | |
SET cm = ','; | |
END IF; | |
END WHILE; | |
RETURN rv; | |
END $$# MySQL returned an empty result set (i.e. zero rows). | |
DELIMITER ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment