DECLARE @MyTable table
(
Col1 int,
col2 int
)
insert @MyTable
values(1, 1),
(2, 1),
(3, 2),
(4, 2),
(5, 3)
DECLARE @YourID int
SET @YourID = 5
;With Superiors
AS
(
SELECT Col1,Col2
FROM @MyTable
WHERE Col1 = @YourID
UNION ALL
SELECT t.Col1,t.Col2
FROM Superiors s
INNER JOIN @MyTable t
ON t.Col1 = s.Col2
WHERE t.Col1 <> t.Col2
)
SELECT Col2
FROM Superiors
OPTION (MAXRECURSION 0)
output
-----------------
Col2
-----------------
3
2
1
------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/