I was trying to retrieve a comma separated string of hierarchy in MySQL using the following procedure :
DROP PROCEDURE IF EXISTS `getAccessibleEntIdz`;
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `getAccessibleEntIdz`(IN entId VARCHAR(20), OUT accessibleEntIds VARCHAR(20))
BEGIN
DECLARE DONE INT DEFAULT FALSE;
DECLARE tEntId VARCHAR(20) DEFAULT '';
DECLARE tParentEntId VARCHAR(20) DEFAULT '';
DECLARE tCursor CURSOR FOR SELECT ent_id, ent_parent_id FROM ent_mst WHERE ent_parent_id = entId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET DONE = TRUE;
OPEN tCursor;
readLoop : LOOP
FETCH tCursor INTO tEntId, tParentEntId;
IF DONE THEN
LEAVE readLoop;
END IF;
SET accessibleEntIds = CONCAT(accessibleEntIds,",",tEntId);
CALL getAccessibleEntIdz(tEntId, accessibleEntIds);
END LOOP;
CLOSE tCursor;
END$$
DELIMITER ;
But the output I receive is NULL. I am making the call in the following manner :
SET @@GLOBAL.max_sp_recursion_depth = 255;
SET @@session.max_sp_recursion_depth = 255;
SET @accessibleEntIds = '';
CALL `getAccessibleEntIdz`('1', @accessibleEntIds);
SELECT @accessibleEntIds;
I tried to debug by putting SELECT command to print variable values in between and found the issue to be that accessibleEntIds variable is unable to maintain values between the calls.
Is there some way I can maintain values between the calls, like global variable or may be like static variables in C language or am I going in wrong direction and there can be some other easier way , please help , I am new to writing procedures!!
Note : The table structure I am using :
CREATE TABLE `ent_mst` (
`ENT_ID` varchar(40) NOT NULL,
`ENT_PARENT_ID` varchar(40) DEFAULT NULL,
`ENT_NAME` varchar(200) NOT NULL,
`ENT_URL` varchar(200) DEFAULT NULL,
`ENT_LOGO_PATH` varchar(256) DEFAULT NULL,
`CREATED_DATE_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`UPDATED_DATE_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`ENT_ID`),
KEY `ENT_PARENT_ID` (`ENT_PARENT_ID`),
CONSTRAINT `ent_mst_ibfk_1` FOREIGN KEY (`ENT_PARENT_ID`) REFERENCES ent_mst (`ENT_ID`)
);
insert into iot_ent_mst values ('1',NULL,'A','url1','loc1',null,null),
('2','1','B','url2','loc2',null,null), ('3','1','C','url5','loc5',null,null),
('4','3','D','url3','loc3',null,null),('5','1','E','url4','loc4',null,null);