Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Every One,

I am working in a asp.Net project in which i am using Sql server 2008.
I have a table "table1".
table name : table1
columns:
empId(Int) empname(varchar)     parentid(int)
1           raj kumar            -1
2           sunil rawat           1 
3           prem kumar            1
4           sunny sohni           2
5           laura dutta           3
6           honey                 3


above is my table. now i want a record of those employee whose parent id is 1.
but i also want that if child of 1 empid like 3 has also child then it should be retrieve. any one know what sql query will be use for this.

please help me..
Posted
Updated 22-May-12 18:45pm
v2
Comments
Nilesh Patil Kolhapur 23-May-12 0:45am    
not clear improve question

1 solution

This depends on how you want to have your data. But for example if you need parent and child on the same row, you could try something like
SQL
SELECT t1.EmpId, t1.EmpName, t2.EmpId, t2.EmpName
FROM table1 t1 left outer join table2 t2
     on t1.EmpId = t2.ParentId


Addition, recursive example
SQL
WITH Employees(ParentId, EmpID, EmpName, Level) AS (
    SELECT t1.ParentId, t1.EmpID, t1.EmpName, 0 AS Level
    FROM table1 t1
    WHERE ParentId = -1
    UNION ALL
    SELECT t2.ParentId, t2.EmpID, t2.EmpName, Level + 1
    FROM table1 t2 inner join Employees e
        ON e.EmpId = t2.ParentId
)
SELECT ParentId, EmpID, EmpName, Level
FROM Employees
 
Share this answer
 
v2
Comments
coolnavjot31 23-May-12 1:09am    
Hello Mika,

thanks for your reply.
please tell me if i would like to retrieve all child records of empID = 1
and sub child of empid=1's child records.

please help me.
Wendelius 23-May-12 1:17am    
Then you would need a recursive query, please see the updated answer.
coolnavjot31 23-May-12 2:08am    
thanks Mika for your help.
coolnavjot31 23-May-12 2:09am    
i find a complete solution from following link:
http://blog.mclaughlinsoftware.com/2009/04/03/t-sql-hierarchical-query/
Wendelius 23-May-12 2:14am    
Looks like a good link :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900