try this !!

  • check this out. if you are having adventure works data base it is there. u can check

    ALTER PROCEDURE [dbo].[uspGetEmployeeManagers]

    @EmployeeID [int]

    AS

    BEGIN

    SET NOCOUNT ON;

    -- Use recursive query to list out all Employees required for a particular Manager

    WITH [EMP_cte]([EmployeeID], [ManagerID], [FirstName], [LastName], [Title], [RecursionLevel]) -- CTE name and columns

    AS (

    SELECT e.[EmployeeID], e.[ManagerID], c.[FirstName], c.[LastName], e.[Title], 0 -- Get the initial Employee

    FROM [HumanResources].[Employee] e

    INNER JOIN [Person].[Contact] c

    ON e.[ContactID] = c.[ContactID]

    WHERE e.[EmployeeID] = @EmployeeID

    UNION ALL

    SELECT e.[EmployeeID], e.[ManagerID], c.[FirstName], c.[LastName], e.[Title], [RecursionLevel] + 1 -- Join recursive member to anchor

    FROM [HumanResources].[Employee] e

    INNER JOIN [EMP_cte]

    ON e.[EmployeeID] = [EMP_cte].[ManagerID]

    INNER JOIN [Person].[Contact] c

    ON e.[ContactID] = c.[ContactID]

    )

    -- Join back to Employee to return the manager name

    SELECT [EMP_cte].[RecursionLevel], [EMP_cte].[EmployeeID], [EMP_cte].[FirstName], [EMP_cte].[LastName],

    [EMP_cte].[ManagerID], c.[FirstName] AS 'ManagerFirstName', c.[LastName] AS 'ManagerLastName' -- Outer select from the CTE

    FROM [EMP_cte]

    INNER JOIN [HumanResources].[Employee] e

    ON [EMP_cte].[ManagerID] = e.[EmployeeID]

    INNER JOIN [Person].[Contact] c

    ON e.[ContactID] = c.[ContactID]

    ORDER BY [RecursionLevel], [ManagerID], [EmployeeID]

    OPTION (MAXRECURSION 25)

    END;

  • I tried this and it works. What am I looking for?

    For better, quicker answers, click on the following...
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

    For better answers on performance questions, click on the following...
    http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

  • Mike01 (5/10/2011)


    I tried this and it works. What am I looking for?

    It would appear that someone has discovered the joy of using recursive CTE's to resolve Adjacency List hierarchies and wanted to share with us. 🙂 Either that or someone was trying to respond to a post and hit the wrong button. :hehe:

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply