tags:

views:

40

answers:

1

Sample Table

Emp Id Emp Name Manger Id
1001   arun     1004
1002   Bharath  1004
1003   Chitra   1004
1004   Devi     1005
1005   Eli      1006
1006   Fatima   1007
1007   Ganesh   1008

when i select manager id 1004 it should display three names arun,bharath,chitra and if i select 1005 it should display devi,arun,bharath,chitra

FYI - ManagerId is same as the EMPId.

How can I prepare the sql with out using functions?

+2  A: 

If you are using SQL Server 2005 and later you can use a common-table expression. In this example, I'm assuming that ManagerId being null indicates the top-most manager.

With HumanResources As
    (
    Select EmpId, EmpName, ManagerId, EmpName As ManagerName
    From Employees
    Where ManagerId Is Null 
    Union All
    Select E.EmpId, E.EmpName, E.ManagerId, H.EmpName
    From Employees As E
        Join HumanResources As H
            On H.EmpId= E.ManagerId
    )
Select EmpId, EmpName, ManagerId, ManagerName
From HumanResources

See Recursive Queries for more.

Thomas
+1: Beat me to it
OMG Ponies
@OMG Ponies - There has to be first time for everything. :)
Thomas
Does that query work? Assuming table Employees with the columns EmpId, EmpName and ManagerId, I get "Msg 207, Level 16, State 1, Line 10Invalid column name 'EmployeeId'."
LittleBobbyTables
@LittleBobbyTables - That's a typo on my part. Have fixed.
Thomas
@Thomas - in the anchor, should "Where ManagerId Is Null" be "Where ManagerId = @ManagerId" (based on OP's example)?
potatopeelings
@potatopeelings - Actually, if you look closely at the data in the OP, the anchor EmpId (1008) isn't listed. So, we don't really know what the anchor is. I simply made a guess.
Thomas