To me it sounds like you want to climb a tree. Therefore, given the test data
DECLARE @tbl TABLE(AccountID INT,AccountName VARCHAR(100),ParentID INT) INSERT INTO @tbl VALUES (1,'Mathew',0), (2,'Philip',1), (3,'John',2), (4,'Susan',2), (5,'Anita',1), (6,'Aimy',1), (7,'Elsa',3), (8,'Anna',7)
I would write a query like this:
DECLARE @AcountID INT=4 ;WITH CTE AS ( SELECT tbl.AccountID, tbl.AccountName, tbl.ParentID FROM @tbl AS tbl WHERE tbl.AccountID=@AcountID UNION ALL SELECT tbl.AccountID, tbl.AccountName, tbl.ParentID FROM @tbl AS tbl JOIN CTE ON CTE.ParentID=tbl.AccountID ) SELECT * FROM CTE WHERE NOT CTE.AccountID=@AcountID
This will return the result as follows:
2 Philip 1 1 Mathew 0
source share