在最近工作中遇到一个树形结构,然后在表单上展示的时候需要把所有的父级用/隔开,但是在起初设置数据库的时候没有字段来标注当前节点是第几级。所以用函数来实现这个功能。
CREATE FUNCTION genParent(name varchar(20)) RETURNS varchar(50)
BEGIN
DECLARE depositName VARCHAR(255) DEFAULT '';
DECLARE sTemp VARCHAR(255) DEFAULT '';
DECLARE num INT(255)DEFAULT 0;
SET sTemp = '';
WHILE deposit !='PLA0' AND deposit is not NULL AND deposit != '' DO
SELECT a.name INTO sTemp FROM t_address_deposit a WHERE a.oid = deposit and a.display = 1;
SELECT a.parentId INTO deposit FROM t_address_deposit a WHERE a.oid = deposit and a.display = 1;
IF num = 0 THEN
set depositName = CONCAT(sTemp,depositName);
ELSE set depositName = CONCAT_WS("/",sTemp,depositName);
end if;
set num = num +1;
END WHILE;
RETURN depositName;
END