SoFunction
Updated on 2025-04-08

Recursive implementation method in stored procedures

A binary tree recursion, find the bottom point on the left.
id Automatic number
pid Parent ID
id_path node path
flg position, 0 left, 1 right
ALTER      PROCEDURE [dbo].[get_class] 

Copy the codeThe code is as follows:
@class int, 
@return int output 
AS 

SELECT  @return=isnull(( select top 1 id  from class where pid=@class and flg=0 ),-2) 

if @return>-1 
    begin 
exec get_class @return,@return output--Why do you need @return here? If you want to get this value in the end, you must pass it in

    end 

else 
    begin 
    SELECT @return=@class 
    end 
GO 
 
In fact, you only need a query statement to find the lowest ID.
The node path contains 1, and the parent node locations are all on the left, take out the largest one.
select top 1 * from class a where id_path like '%1,%' and flg=0 and (select flg from class where id=)=0 order by id desc