• subscribe
December 20, 2000 12:00 AM

Answer to Recursion Challenge

SQL Server Pro
InstantDoc ID #16197

In the article "Manipulating Hierarchies with UDFs" (January 2001), I presented a nonrecursive UDF called ufn_GetSubtree that returns a whole subtree under a given manager. In the sidebar "Test Your Recursion Powers!" I presented the following challenge: "To test your understanding of recursion and user-defined functions (UDFs), solve the following puzzle: Can you implement the function ufn_GetSubtree by using a recursive algorithm? Note that you aren’t required to return the lvl and path columns, rather just employee details of the whole subtree under a given manager." The recursive ufn_GetSubtree function returns a table variable called @tree with the same schema as the Employees table. The function performs the following steps:

  • Inserts into the @tree table variable the row of the employee whose employee ID was provided to the function as an argument.
  • Forms a loop that iterates through all of the direct subordinates of the employee provided to the function as an argument.
  • Inserts each direct subordinate’s subtree into the @tree table variable.

Note that the last step is actually a recursive call to the ufn_GetSubtree function. Listing 1 shows the code for the recursive ufn_GetSubtree function.



ARTICLE TOOLS

Comments
  • anthony
    11 years ago
    Jun 19, 2001

    Wouldn't:-

    CREATE FUNCTION dbo.ufn_GetSubtree2
    (
    @mgrid AS int
    )
    RETURNS @tree TABLE
    (
    empid int NOT NULL,
    mgrid int NULL,
    empname varchar(25) NOT NULL,
    salary money NOT NULL
    )
    AS
    BEGIN

    INSERT INTO @tree
    SELECT * FROM Employees WHERE mgrid = @mgrid




    DECLARE @curemp AS int

    SELECT @curemp = MIN(empid) FROM @tree
    WHERE mgrid = @mgrid

    WHILE @curemp IS NOT NULL
    BEGIN

    INSERT INTO @tree
    SELECT * FROM ufn_GetSubtree2(@curemp)

    SELECT @curemp = MIN(empid) FROM @tree
    WHERE mgrid = @mgrid AND empid > @curemp

    END

    RETURN

    END
    GO

    be a better solution

You must log on before posting a comment.

Are you a new visitor? Register Here