Here is a table called code .
p_code column is the parent code

And the stored procedure should return a record set joined by p_code as follows:

The procedure works well, except for the first time (after reconnecting MYSQL, it returns null!). What is wrong with him?
The procedure is stored here.
BEGIN DECLARE _CODE bigint(20); DECLARE _P_CODE bigint(20); DECLARE _SORT bigint(20); DECLARE _pre_P_CODE bigint(20); DECLARE CONTINUE HANDLER FOR NOT FOUND SET @CODE = NULL; SET _P_CODE = @CODE; SET _CODE = ''; SET _SORT = 0; SET _pre_P_CODE = ''; IF @CODE IS NULL THEN RETURN NULL; END IF; LOOP SELECT CODE, P_CODE, SORT, CODE_NAME, CODE_LEVEL INTO @CODE, @P_CODE, @SORT, @CODE_NAME, @CODE_LEVEL FROM CODE WHERE LANGUAGE = @LANGUAGE AND P_CODE = _P_CODE AND SORT > _SORT ORDER BY SORT limit 1; IF @CODE IS NOT NULL OR _P_CODE = @start_with THEN SET @level = @level + 1; RETURN @CODE; END IF; SET @level := @level - 1; SELECT CODE, P_CODE, SORT INTO _CODE, _P_CODE, _SORT FROM CODE WHERE CODE = _P_CODE; END LOOP; END
And the procedure is called like that. This SQL will return the second image above.
SELECT menu_connect_by_p_code() AS CODE, @level as level, @P_CODE as p_code, @SORT as sort, @CODE_NAME as CODE_NAME, @CODE_LEVEL as CODE_LEVEL FROM ( SELECT @start_with := 6001,@LANGUAGE := 'en' , @CODE := @start_with, @level := 0 ) vars, code WHERE @CODE IS NOT NULL
I do not understand why it returns null for the first time . Is there something wrong with the procedure or the kind of MYSQL error?
------------------------------- edit --------------- --- ------------------
RolandoMySQLDBA, rsanchez, I tried my version, but I remain the same. It returns multiple rows, and some columns have a null value.

------------------------------- edit2 --------------- --- ------------------
You can see here: http://sqlfiddle.com/#!2/aa033/1