程序与该示例配合良好。但不能在我自己的数据库中工作。似乎我在创建程序时做错了什么。 这是我的db的过程:
DELIMITER $$
DROP FUNCTION IF EXISTS `demo`.`GetParentIDByID` $$
CREATE FUNCTION `demo`.`GetParentIDByID` (GivenID INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE rv INT;
SELECT IFNULL(user_by,-1) INTO rv FROM
(SELECT user_by FROM users WHERE id = GivenID) A;
RETURN rv;
END $$
DELIMITER ;
以下过程的SQL查询工作正常。它基本上是获得节点的parent_id:
SELECT id,GetParentIDByID(id) FROM users;
当我试图获得祖先时会出现问题。这是我正在使用的程序:
DELIMITER $$
DROP FUNCTION IF EXISTS `demo`.`GetAncestry` $$
CREATE FUNCTION `demo`.`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(user_by,-1) INTO ch FROM
(SELECT user_by FROM users WHERE id = ch) A;
IF ch > 0 THEN
SET rv = CONCAT(rv,cm,ch);
SET cm = ',';
END IF;
END WHILE;
RETURN rv;
END $$
DELIMITER ;
SQL查询:
SELECT id,GetAncestry(id) FROM users;