Assuming you have SQL 2005 or later you can use a recursive common table expression (CTE) for this.You can search here for plenty of examples (search for hierarchy or parent-child).But here is a quick example of a recursive CTE based on your sample:declare @t table (CompanyID int, CompanyName varchar(10), ParentCompanyID int, UserID int)insert @tselect 0, 'klm', -1, 1000union all select 1, 'abc', 2, 1001union all select 2, 'xyz', 0, 1002union all select 3, 'pqr', 2, 1003union all select 4, 'mno', 3, 1004;with rcte as ( select companyid, companyname, parentCompanyID, Userid from @t where userid = 1002 union all select t.companyid, t.companyname, t.parentCompanyID, t.Userid from rcte r join @t t on t.parentCompanyID = r.companyid)select * from rcteOUTPUT:companyid companyname parentCompanyID Userid----------- ----------- --------------- -----------2 xyz 0 10021 abc 2 10013 pqr 2 10034 mno 3 1004
Do you need help incorporating this into a stored procedure as well or are you good on that part?Be One with the OptimizerTG