SQL Server 2005 recursive query with loops in data - is it possible?

前端 未结 10 1845
野趣味
野趣味 2020-12-06 03:29

I\'ve got a standard boss/subordinate employee table. I need to select a boss (specified by ID) and all his subordinates (and their subrodinates, etc). Unfortunately the rea

10条回答
  •  星月不相逢
    2020-12-06 04:08

    You need a some method to prevent your recursive query from adding User ID's already in the set. However, as sub-queries and double mentions of the recursive table are not allowed (thank you van) you need another solution to remove the users already in the list.

    The solution is to use EXCEPT to remove these rows. This should work according to the manual. Multiple recursive statements linked with union-type operators are allowed. Removing the users already in the list means that after a certain number of iterations the recursive result set returns empty and the recursion stops.

    with UserTbl as -- Selects an employee and his subordinates.
    (
        select a.[User_ID], a.[Manager_ID] from [User] a WHERE [User_ID] = @UserID
        union all
        (
          select a.[User_ID], a.[Manager_ID] 
            from [User] a join UserTbl b on (a.[Manager_ID]=b.[User_ID])
            where a.[User_ID] not in (select [User_ID] from UserTbl)
          EXCEPT
            select a.[User_ID], a.[Manager_ID] from UserTbl a 
         )
    )
    select * from UserTbl;
    

    The other option is to hardcode a level variable that will stop the query after a fixed number of iterations or use the MAXRECURSION query option hint, but I guess that is not what you want.

提交回复
热议问题