Tuesday, May 13, 2008

Self Join - Sql server

Self-joins : A self-join is a query in which a table is joined  to itself.  Self-joins are used to compare values in a column with other values in the same column in the same table

Example:  In this example i am tring to insert data into Employee table with emp id, manager id. Manager id referes same tables emplid. Finally by using innerjoin i wanted to get data with manager name rather than manager id.

1. Create table
CREATE TABLE dbo.Employee

(

empId int NOT NULL IDENTITY (1, 1),

empName nvarchar(50) NOT NULL,

managerId int NULL

) ON [PRIMARY]

2. Insert Data into Table
1,Madhu,NULL
2,Bala,1
3,Krishna,1
4,Ram,1

3. SQL Query - Self Join

select a.empId, a.empName as Employee , b.empName as ManagerName

from Employee a, Employee b where b.empId=a.managerId


4. Output
2,Bala,Madhu
3,Krishna,Madhu
4,Ram,Madhu

Posted by at 06:11:33
Comments

Leave a Reply