;with cte as( select id,ParentCategoryId from Category where id = 17 union all select a.id,a.ParentCategoryId from Category a join cte b on a.ParentCategoryId = b.id where a.id is not null) select * from cte