Thursday 10 May 2012

Self Join in SQL SERVER



DECLARE @Temp TABLE(ID INT, Name VARCHAR(10),PID INT)

INSERT INTO @Temp Values(1,'A',NULL)
INSERT INTO @Temp Values(2,'B',1)
INSERT INTO @Temp Values(3,'C',1)
INSERT INTO @Temp Values(4,'D',2)
INSERT INTO @Temp Values(5,'E',2)

SELECT t1.ID,
            t1.Name,
            t2.Name AS Parent
FROM @Temp t1
LEFT JOIN @Temp t2 on t2.ID = t1.PID

No comments:

Post a Comment