MySql ::存储过程递归

时间:2013-01-14 08:49:59

标签: mysql stored-procedures recursion

如何重写以下SP以面对MySQL中的递归限制:

CREATE DEFINER = `root`@`localhost` PROCEDURE `SP_DeleteParentDirectory`(pParentID INT,pIsFolder INT,pReferenceID INT)
BEGIN   
SET @@SESSION.max_sp_recursion_depth = 255;
    SET @IsFolder= NULL;
    SET @ChildID= NULL;
    SET @ReferenceID= NULL;
    IF ( pIsFolder= 2) THEN
                SELECT  FileID INTO @ChildID FROM filesinfo WHERE ParentID= pParentID LIMIT 1;
                WHILE (@ChildID IS NOT NULL) DO
                         SELECT  filesinfo.IsFolder,filesinfo.ReferenceID INTO @IsFolder,@ReferenceID FROM filesinfo WHERE filesinfo.FileID = @ChildID;
                        CALL SP_DeleteParentDirectory(@ChildID,@IsFolder,@ReferenceID);             
                        SELECT filesinfo.FileID INTO @ChildID FROM filesinfo WHERE ParentID= pParentID LIMIT 1;
                END While;
    END IF;
    DELETE FROM filesinfo Where  filesinfo.FileID= pParentID;
    IF EXISTS( SELECT  * FROM  filesrefrences WHERE filesrefrences.ReferenceID = pReferenceID AND filesrefrences.RefrenceCount>1) THEN
            UPDATE filesrefrences
            SET RefrenceCount= RefrenceCount-1 WHERE  filesrefrences.ReferenceID = pReferenceID;            
    ELSE            
            SET @ReferenceKey= NULL;
            Select filesrefrences.RefrenceKey INTO @ReferenceKey FROM filesrefrences WHERE filesrefrences.ReferenceID= pReferenceID;
            IF NOT EXISTS(SELECT * FROM deletefilesreferences WHERE deletefilesreferences.FileReference= @ReferenceKey) THEN
            INSERT INTO deletefilesreferences (deletefilesreferences.FileReference)VALUES(@ReferenceKey);
            END IF;
            DELETE FROM filesrefrences where filesrefrences.ReferenceID = pReferenceID;         
    END IF;
    -- CALL SP_DeleteFileInfo(pParentID,pReferenceID);      
    -- SELECT * FROM deletefilesreferences;
    -- CALL SP_GetDeletedReferences();
END;

不使用此sts:

SET @@ SESSION.max_sp_recursion_depth = 255; ” 我的意思是它可以与层次结构数据交互而不会递归。

1 个答案:

答案 0 :(得分:1)

如果设置了max_sp_recursion_depth,Mysql在PROCEDURE中最多允许255次递归。

风险很大,因为将来某个时候所需的递归深度有可能超过255。

因此,使用 INOUT 变量替换return_result,可以更好地使用过程替换函数。