表结构:id,pid自关联的树形结构
DROP PROCEDURE IF EXISTS getAncestros;
DELIMITER $$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
PROCEDURE `getAncestros`(IN deptId INT,INOUT ances VARCHAR(1000))
/*LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'*/
BEGIN
DECLARE pid INT DEFAULT 0;
SET pid = (SELECT parent_id FROM sys_dept WHERE dept_id = deptId);
IF pid <> 0 AND LENGTH(ances) < 999 THEN
SET ances = CONCAT(pid,',',ances);
CALL getAncestros(pid,ances);
END IF;
END$$
DELIMITER ;
DROP PROCEDURE IF EXISTS updateDepat;
SET @@max_sp_recursion_depth = 100;
DELIMITER $$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
PROCEDURE `updateDepat`()
/*LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'*/
BEGIN
DECLARE total INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE pid INT DEFAULT 0;
DECLARE cid INT DEFAULT 0;
DECLARE ace VARCHAR(1000) DEFAULT '';
SET total = (SELECT COUNT(1) FROM `sys_dept`);
WHILE i < total DO
SET ace = '';
SET pid = (SELECT parent_id FROM `sys_dept` LIMIT i,1);
SET cid = (SELECT dept_id FROM `sys_dept` LIMIT i,1);
CALL getAncestros(cid,ace);
SET ace = LEFT(ace,LENGTH(ace)-1);
IF pid <> 0 THEN
UPDATE `sys_dept` SET ancestors = ace,update_time = NOW() WHERE dept_id = cid;
END IF;
SET i=i+1;
END WHILE;
END$$
DELIMITER ;
CALL updateDepat();