Email Id : phpmk888@gmail.com
function and procedure MySQL hierarchical recursive query
Below you will find all code to create the table and the stored procedures to manage hierarchical trees in MySQL.
DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION `get_emp`(emp_id VARCHAR(255)) RETURNS VARCHAR(255) CHARSET latin1
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE ids INT;
DECLARE dat VARCHAR(255);
DECLARE cur CURSOR FOR SELECT id FROM padp WHERE FIND_IN_SET(manager, emp_id);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET dat = '';
OPEN cur;
ins_loop: LOOP
FETCH cur INTO ids;
IF done THEN
LEAVE ins_loop;
END IF;
SET dat = CONCAT(dat,',',ids);
END LOOP;
CLOSE cur;
RETURN dat;
END$$
DELIMITER $$
#USE `test`$$
DROP PROCEDURE IF EXISTS `GET_DATA`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `GET_DATA`(IN emp_id VARCHAR(255))
BEGIN
DECLARE dat VARCHAR(255);
SET dat = '';
ins_loop: LOOP
SET emp_id = get_emp(emp_id);
IF emp_id='' THEN
LEAVE ins_loop;
END IF;
SET dat = CONCAT(dat,emp_id);
END LOOP;
SELECT dat;
END$$
DELIMITER ;
/***
* Table : padp, id,manager
*
* @emp_id = 100
* CALL Procedure
****/
CALL GET_DATA(100);
////
function EDITED ///
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE ids VARCHAR(255);
DECLARE dat VARCHAR(255);
DECLARE cur CURSOR FOR SELECT emp_code FROM employee_master WHERE FIND_IN_SET(reporting_manager_id, emp_id);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET dat = '';
OPEN cur;
ins_loop: LOOP
FETCH cur INTO ids;
IF done THEN
LEAVE ins_loop;
END IF;
SET dat = CONCAT(dat,',',ids);
END LOOP;
CLOSE cur;
RETURN dat;
END
//*******
******/
BEGIN
DECLARE dat VARCHAR(255);
SET dat = '';
ins_loop: LOOP
SET emp_id = getHisReportingEmp(emp_id);
IF emp_id='' THEN
LEAVE ins_loop;
END IF;
SET dat = CONCAT(dat,emp_id);
END LOOP;
SELECT dat;
END
/*---------------------------------*/
Comments
Post a Comment