CREATE FUNCTION `getRoot`(pid INT(11),pdepth INT(11)) RETURNS int(11) READS SQL DATA DETERMINISTIC BEGIN DECLARE tdepth INT(11) UNSIGNED DEFAULT 100; DECLARE troot INT(11) UNSIGNED; DECLARE tfin INT(11) UNSIGNED; SET tfin = pid; WHILE (tdepth > (pdepth + 1)) DO SELECT `post_depth`,`post_parent` FROM `posts` where `post_id` = tfin INTO tdepth,troot; SET tfin = CASE WHEN (tdepth <= pdepth) THEN (tfin) ELSE (troot) END; END WHILE; RETURN tfin; END CREATE FUNCTION `sortThread`(pid INT(11)) RETURNS longtext CHARSET latin1 READS SQL DATA DETERMINISTIC BEGIN DECLARE tcount INT(11) UNSIGNED DEFAULT 50; DECLARE tdepth INT(11) UNSIGNED DEFAULT 50; DECLARE troot INT(11) UNSIGNED ZEROFILL; DECLARE tfin INT(11) UNSIGNED ZEROFILL; DECLARE tstr LONGTEXT DEFAULT NULL; SET tfin = pid; SET tstr = CONCAT_WS(',',tstr, REVERSE(tfin)); infl: WHILE (1) DO SELECT `post_depth`,`post_parent` FROM `posts` where `post_id` = tfin INTO tdepth,troot; IF troot = 0 THEN LEAVE infl; ELSEIF tcount <= 0 THEN LEAVE infl; END IF; SET tfin = troot; SET tstr = CONCAT_WS(',',tstr, REVERSE(troot)); SET tcount = tcount - 1; END WHILE; RETURN REVERSE(tstr); END